I want a
to be rounded to 13.95.
>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
The ro
float_number = 12.234325335563
round(float_number, 2)
This will return;
12.23
round function takes two arguments; Number to be rounded and the number of decimal places to be returned.Here i returned 2 decimal places.
You can modify the output format:
>>> a = 13.95
>>> a
13.949999999999999
>>> print "%.2f" % a
13.95
We multiple options to do that : Option 1:
x = 1.090675765757
g = float("{:.2f}".format(x))
print(g)
Option 2: The built-in round() supports Python 2.7 or later.
x = 1.090675765757
g = round(x, 2)
print(g)
The method I use is that of string slicing. It's relatively quick and simple.
First, convert the float to a string, the choose the length you would like it to be.
float = str(float)[:5]
In the single line above, we've converted the value to a string, then kept the string only to its first four digits or characters (inclusive).
Hope that helps!
Try the code below:
>>> a = 0.99334
>>> a = int((a * 100) + 0.5) / 100.0 # Adding 0.5 rounds it up
>>> print a
0.99
In Python 2.7:
a = 13.949999999999999
output = float("%0.2f"%a)
print output