I want a
to be rounded to 13.95.
>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
The round
function does not work the way I expected.
I want a
to be rounded to 13.95.
>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
The round
function does not work the way I expected.
Results:
There are new format specifications, String Format Specification Mini-Language:
You can do the same as:
Note that the above returns a string. In order to get as float, simply wrap with
float(...)
:Note that wrapping with
float()
doesn't change anything:Use
instead of
Because the latter may lead to output errors when trying to output multiple variables (see comments).
TLDR ;)
The rounding problem at input / output has been solved by Python 2.7.0 and 3.1 definitively.
Infinite test:
Documentation
See the Release notes Python 2.7 - Other Language Changes the fourth paragraph:
The related issue
More information:: The formatting of
float
before Python 2.7 was similar to the currentnumpy.float64
. Both types use the same 64 bit IEEE 754 double precision with 52 bit mantissa. A big difference is thatnp.float64.__repr__
is formatted frequently with an excessive decimal number so that no bit can be lost, but no valid IEEE 754 number exists between 13.949999999999999 and 13.950000000000001. The result is not nice and the conversionrepr(float(number_as_string))
is not reversible. On the other hand:float.__repr__
is formatted so that every digit is important; the sequence is without gaps and the conversion is reversible. Simply: If you perhaps have a numpy.float64 number, convert it to normal float in order to be formatted for humans, not for numeric processors, otherwise nothing more is necessary with Python 2.7+.To round a number to a resolution, the best way is the following one, which can work with any resolution (0.01 for two decimals or even other steps):
In Python 2.7: