Why is python returning 5.789999999999999
for sum([1.23, 4.56])
and how do I get it to return the expected 5.79
Asked
Active
Viewed 24 times
2

newToScala
- 397
- 4
- 16
-
Use `round` with 2 as the second parameter to round to two decimal places. Otherwise floating point error will be there. – Arnav Borborah Sep 20 '19 at 18:29
-
I don't know that the values will always have two decimal places – newToScala Sep 20 '19 at 18:29
-
Thomas - that isn't python specific. I am asking the best practice in python – newToScala Sep 20 '19 at 18:31
-
@newToScala if you need precise decimal values don't use `float` objects, which cannot precisely represent those values, and which rely on floating point arithmetic. Use `decimal.Decimal` objects. – juanpa.arrivillaga Sep 20 '19 at 18:32