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.
Nobody here seems to have mentioned it yet, so let me give an example in Python 3.6's f-string/template-string format, which I think is beautifully neat:
It works well with longer examples too, with operators and not needing parens:
It's doing exactly what you told it to do and is working correctly. Read more about floating point confusion and maybe try decimal objects instead.
I feel that the simplest approach is to use the
format()
function.For example:
This produces a float number as a string rounded to two decimal points.
Most numbers cannot be exactly represented in floats. If you want to round the number because that's what your mathematical formula or algorithm requires, then you want to use round. If you just want to restrict the display to a certain precision, then don't even use round and just format it as that string. (If you want to display it with some alternate rounding method, and there are tons, then you need to mix the two approaches.)
And lastly, though perhaps most importantly, if you want exact math then you don't want floats at all. The usual example is dealing with money and to store 'cents' as an integer.
With Python < 3 (e.g. 2.6 or 2.7), there are two ways to do so.
But note that for Python versions above 3 (e.g. 3.2 or 3.3), option two is preferred.
For more information on option two, I suggest this link on string formatting from the Python documentation.
And for more information on option one, this link will suffice and has information on the various flags.
Reference: Convert floating point number to a certain precision, and then copy to string
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:
One alternative and solution to your problems would be using the
decimal
module.