Rounding Float Number to the Nearest Tenth
Hi I Have a Number Like 1.3333333333(The Result of Python Division) to Round of to the Nearest Tenth Input 1.333333333 Output 1.34 or 1.3 Here Is What I Tried...
Hi i have a number like 1.3333333333(THE RESULT OF PYTHON DIVISION) to round of to the nearest tenth
Input
1.333333333
Output
1.34 or 1.3
Here is what i tried
def round(self,oj):
try:
(bd,ad) = oj.split(".")
if int(ad[1]) >5:
up = True
else:
up= False
if up:
if ad[0]==9:
oj = str(int(bd)+1)
else:
oj = str(bd)+"."+str(int(ad[0])+1)
else:
oj =str( bd)+"."+ad[0]
except IndexError:
pass
return float(oj)
But i believe there is a better way to do it so please tell any suggestions you have
1 Answer
There are several ways you can round the number in python.
1) Use the round() function.
round(1.33333, 1) #return float
Output: 1.3
2) Use the format() function.
"{0:.1f}".format(1.33333) #return string
Output: 1.3
3) Use a format-string with the "%" operator
"%.1f" % 1.333333 #return string
Output: 1.3