How do I convert 45.34531 to 45.3?
3 Answers
Are you trying to represent it with only one digit:
print("{:.1f}".format(number)) # Python3 print "%.1f" % number # Python2 or actually round off the other decimal places?
round(number,1) or even round strictly down?
math.floor(number*10)/10 3 Comments
Devesh Saini
Is there any chance that your 1st and 3rd solution gives different results? I think they both are exactly same @relet
relet
Try number=-2.55. They also return different types.
Sanyam Jain
@DeveshSaini try number 2.36. 1st will give 2.4, 3nd will give 2.3
>>> "{:.1f}".format(45.34531) '45.3' Or use the builtin round:
>>> round(45.34531, 1) 45.299999999999997 4 Comments
Nathan
Update: Round gives me 45.3 nowdays.
Dave Halter
This is answer is correct but the formatting is way to complicated IMO. You should just write
"{:.1f}".format(45.34531).dogmatic69
@DaveHalter, writing out
0.1 instead of .1 is way to complicated, how can anyone even follow that code...Dave Halter
There's also a zero in front that is not necessary. I also think that nobody really understands the format language so keeping it simple is preferred IMO. Now with Python 3.6 I would recommend writing it like this:
f"{number:.1f}".