83
inaba
7y

Try not to use floating point numbers in places where precision is important. Like for instance, money. Always store the base value where it makes the most sense

Comments
  • 17
    The word "anything" are spelt differently in the code and the output. ++ nonetheless
  • 5
    there are law rules to work with money. they allow to round floats in specific way.
  • 1
    That's why, for example, .NET was given the System.Decimal type :P
  • 2
    @extroot nice try :D
  • 0
    Isn't there a setPrecision method in C++?

    I use it for float or double data type.
  • 0
    How can .2 + .1 NOT = .3
  • 2
    Fira Code with ligatures I see πŸ€”πŸ€”πŸ‘
  • 2
    @seraphimsystems because decimal numbers don't exist in computers and they operate with binary numbers. What some smart people have figured out is that you can cheat the computers to think its using decimal numbers,which occasionally leads to data loss, or gain as I think it is in this case
  • 1
    @inaba Haskell:

    0.2 ~?~ 0.3 - 0.1
    within ulp (1-0.7) 0.3

    It's nice to have approximation functions.
  • 0
    Use abs(a - b) < epsilon. An example epsilon might be 1e-9.
  • 6
    That is why our legacy system (before using .net) always stored money in pennies as integers.
  • 1
    If you don't want to work with floating point numbers, then don't use a computer.
  • 0
    @inaba but you just work out the number as you would with binary and then apply a decimal at the right point? It doesn't seem so hard, maybe it wouldn't be fast but it should be pretty easy to emulate this in software...
  • 1
    @bahua I do think it's kind of silly that so many languages aren't handling it in smarter ways. Like having a fractional num type.
  • 0
    @seraphimsystems Decimal numbers in binary are a bit more complex for a good reason. Take 99 for instance, it's 1100011 in binary. If you had that as your decimal number and added .01 it wouldn't really overflow like you would expect it. You would just end up with .1 instead
Add Comment