I want a
to be rounded to 13.95.
>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
The ro
The Python tutorial has an appendix called Floating Point Arithmetic: Issues and Limitations. Read it. It explains what is happening and why Python is doing its best. It has even an example that matches yours. Let me quote a bit:
>>> 0.1 0.10000000000000001
you may be tempted to use the
round()
function to chop it back to the single digit you expect. But that makes no difference:>>> round(0.1, 1) 0.10000000000000001
The problem is that the binary floating-point value stored for
“0.1”
was already the best possible binary approximation to1/10
, so trying to round it again can’t make it better: it was already as good as it gets.Another consequence is that since
0.1
is not exactly1/10
, summing ten values of0.1
may not yield exactly1.0
, either:>>> sum = 0.0 >>> for i in range(10): ... sum += 0.1 ... >>> sum 0.99999999999999989
One alternative and solution to your problems would be using the decimal module.