How to "round" a float in Python?

16

I have this sum:

total = 0.1 + 0.2
print total #retorna 0.30000000000000004

How would I "round" the decimal places and return only the number of houses added? 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
#...
    
asked by anonymous 21.12.2014 / 02:15

3 answers

22

This is a recurring question. This rounding "problem" occurs by the way the fluent 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 that and they work well in many scenarios. When you want accuracy, probably because you're 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 display the number with the number of decimal places you want. Most of the time you will get the number you want. Not at all.

In this answer in SO there are 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

Formatting Documentation .

    
21.12.2014 / 02:33
7

Very simple:

def arredondar(num):
    return float( '%g' % ( num ) )
print(arredondar(0.1 + 0.2)

The output: 0.3 .

    
09.01.2015 / 12:46
1

You can use .format You go through something like: print ("text that will use {}". Format (the variable you used)) Note that within the quotation marks "" there are two {} within {} you will put {: .Nf} "N" is a number that will be rounded off, for example: print ("Value is: {: .2f}". (sla) With this the variable that I have called sla will be surrounded by your comma after the comma and if you want, you can also by just {:. F} that will practically take the number and thus round it. This works for any number that places before f within {}

    
26.08.2017 / 20:58