How to "round" a float in Python?

Question:

I have this sum:

total = 0.1 + 0.2
print total #retorna 0.30000000000000004

How would I go about "rounding" the decimal places and returning only the number of places added together? Example:

totalA = 0.1 + 0.2     #retornaria 0.3
totalB = 0.32 + 0.25   #retornaria 0.57
totalC = 0.358 + 0.1   #retornaria 0.458
#...

Answer:

This is a recurring question. This rounding "problem" is due to the way the floating point number is stored and manipulated in the CPU itself, and is not Python dependent. The processor works with binary floating point and not decimal, so there are these little inaccuracies. Languages ​​end up, by table, incorporating this.

Numbers like this are very quick to work with and they work well in many scenarios. When you want to have exact precision, 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 to present the number with the desired number of decimal places. Most of the time it will display the number you want. Not all.

In this answer on the OS there are some alternatives for 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 it on GitHub for future reference .

Formatting documentation .

Scroll to Top