How to "round" a float in Python?

Asked

Viewed 80,372 times

25

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 places summed? 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
#...
  • 1

    Your doubt is just like showing rounded or you’re in doubt because 0.1 + 0.2 gives 0.30000000000000004 and not 0.3?

  • @Bigown It’s like showing rounded.

  • 1

    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.

5 answers

32


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.

10

Very simple:

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

The way out: 0.3.

5

You can use the . format You go for something like: print("text that will use {}".format(the variable you used)) Note that inside the quotes "" go two {} inside the {} you will put {:. Nf} "N" is a number that will be rounded, for example: print("The value is: {:.2f}".format(sla)) With this the variable I called sla will be aredondada two houses after the comma and if you want can also by only {:. f} that will practically take out the number and so round it. This works for any number you place before the f inside the {}

3

use a truncation function

import math


def truncate(number, digits) -> float:
    stepper = pow(10.0, digits)
    return math.trunc(stepper * number) / stepper


print(truncate((0.1 + 0.2), 2))

-4

You can use the round() function, which gets the number to be rounded and the number of decimal places you want to round to:

>>> 0.1+0.2
0.300000000000000004

>>> # round com duas casas decimais:

>>> round(0.1+0.2,2)
0.3
  • Not the best strategy. The round function presents a problem, test: round(2.5) , round(2.51) , round(3.5) and round(1.5) note that the function has erratic behavior, with the reason explained in that reply

Browser other questions tagged

You are not signed in. Login or sign up in order to post.