-3

In python 2.7, i am adding below numbers in the given order(since i am getting, those data from db in the same order)

24.73+1+.33+.33+.33+.33+.33+.33+.33+.33+.33+.33+.33+.33+.33+.33+.33+.33+.33+.33+.33+8 summation is coming as 39.99999999999997 but actual answer is 40

any suggestion will be helpful. thanks in advance

Vivek
  • 341
  • 1
  • 5
  • 15
  • 3
    Possible duplicate of [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Idos Mar 17 '16 at 12:05

1 Answers1

1

From the Python documentation on floats:

Note that this is in the very nature of binary floating-point: this is not a bug in Python, and it is not a bug in your code either. You’ll see the same kind of thing in all languages that support your hardware’s floating-point arithmetic (although some languages may not display the difference by default, or in all output modes).

So, this is just the way floating numbers work. To get the results you are expecting, try using the decimal module.

>>> 24.73+1+.33+.33+.33+.33+.33+.33+.33+.33+.33+.33+.33+.33+.33+.33+.33+.33+.33+.33+.33+8
39.99999999999997
>>> s = "24.73+1+.33+.33+.33+.33+.33+.33+.33+.33+.33+.33+.33+.33+.33+.33+.33+.33+.33+.33+.33+8"
>>> sum([Decimal(x) for x in s.split('+')])
Decimal('40.00')
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284