-1

I know that if I use float numbers when calculating money, I will have the risk of getting incorrect results if the results are rounded to lower precision, isn't the results equal?

>>> 234042163/(2**24)
13.949999988079071
>>> (Decimal("234042163")/(Decimal("2")**Decimal("24")))
Decimal('13.949999988079071044921875')
>>> (Decimal("234042163")/(Decimal("2")**Decimal("24"))).quantize(Decimal("1.00000000"))
Decimal('13.94999999')
>>> round(234042163/(2**24), 8)
13.94999999
gawry
  • 762
  • 1
  • 9
  • 18
  • Try adding a very large number to a very small number and you will see the system crumble. – Compass Jul 07 '16 at 13:37
  • Even if I should use lower precision? According to a local financial institution, I'm supposed to use a precision of 8 numbers when calculating returns on investment. – gawry Jul 07 '16 at 13:39
  • 1
    Yes, even if you are using lower precision. $100,000,000.00 + $5.74 with 8 units of precision is a loss of financial data. – Compass Jul 07 '16 at 13:51

1 Answers1

1

No, it isn't. Floating point numbers always have the full precision and when you do any operations with them the inaccuracies will cause issues. Also the main issue isn't the limited accuracy but the fact that some numbers cannot be represented accurately. Just like you can't represent 1/3 accurately as a decimal, you can't represent some numbers accurately with floats.

If you perform operations with these numbers there will be problems even if you try to round them to a certain number of digits.

The only way to ever have proper currency calculations is using scaled integers, meaning the decimal type in many languages. It can represent the numbers accurately on its range and will not cause issues.

Sami Kuhmonen
  • 30,146
  • 9
  • 61
  • 74