0

I am using python 3.8.5 to sum a list of floats as follows:

>> prices = [12.3, 11.99, 1.99, 5]
>> sum(prices)
31.279999999999998

here as you see, the sum function is returning a rounded result where the real sum is equal to 31.28. What sum has a same behaviour?

Mehdi Ben Hamida
  • 893
  • 4
  • 16
  • 38

1 Answers1

0

This is caused by floats implementation, not sum. You might use decimal.Decimal to avoid that problem.

import decimal
prices = [decimal.Decimal("12.3"), decimal.Decimal("11.99"), decimal.Decimal("1.99"), decimal.Decimal("5")]
print(sum(prices))

Output:

31.28
Daweo
  • 31,313
  • 3
  • 12
  • 25