Reputation: 37
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
Upvotes: 0
Views: 1249
Reputation: 141
There are several ways you can round the number in python.
round()
function.round(1.33333, 1) #return float
Output: 1.3
format()
function."{0:.1f}".format(1.33333) #return string
Output: 1.3
"%.1f" % 1.333333 #return string
Output: 1.3
Upvotes: 2