That’s a recurring question. This rounding "problem" occurs by the way the floating point number is stored and manipulated in the CPU itself, and does not depend on Python. The processor works with binary floating point and not decimal, so there are these small inaccuracies. The languages end up, by table, incorporating this.
It’s very fast to work with numbers like this and they work well in many scenarios. When you want to have exact accuracy, probably because you are working with monetary values, you need to use a decimal type or something similar that guarantees the necessary precision.
What you can do in Python or any language is present the number with the desired number of decimals. Most of the time you will present the number you want. Not at all.
In that response in the OS has some alternatives to the presentation:
>>> a=13.946
>>> print(a)
13.946
>>> print("%.2f" % a)
13.95
>>> round(a,2)
13.949999999999999
>>> print("%.2f" % round(a,2))
13.95
>>> print("{0:.2f}".format(a))
13.95
>>> print("{0:.2f}".format(round(a,2)))
13.95
>>> print("{0:.15f}".format(round(a,2)))
13.949999999999999
I put in the Github for future reference.
Documentation of formatting.
Your doubt is just like showing rounded or you’re in doubt because
0.1 + 0.2
gives0.30000000000000004
and not0.3
?– Maniero
@Bigown It’s like showing rounded.
– Kazzkiq
If it is financial calculation that you are trying to do, do not go with float and go straight to Decimal to solve these arrendondamentos problems. https://docs.python.org/3.5/library/decimal.html Then apply the specialized quantize() method together with preferred rounding modes.
– Undefined Behavior