How do I convert 45.34531
to 45.3
?
Asked
Active
Viewed 3.5e+01k times
3 Answers
239
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

relet
- 6,819
- 2
- 33
- 41
-
Is there any chance that your 1st and 3rd solution gives different results? I think they both are exactly same @relet – Devesh Saini Feb 11 '17 at 12:43
-
1Try number=-2.55. They also return different types. – relet Feb 11 '17 at 19:10
-
@DeveshSaini try number 2.36. 1st will give 2.4, 3nd will give 2.3 – Sanyam Jain Jan 22 '18 at 02:51
40
>>> "{:.1f}".format(45.34531)
'45.3'
Or use the builtin round:
>>> round(45.34531, 1)
45.299999999999997

miku
- 181,842
- 47
- 306
- 310
-
13
-
2This is answer is correct but the formatting is way to complicated IMO. You should just write `"{:.1f}".format(45.34531)`. – Dave Halter Apr 04 '18 at 22:13
-
@DaveHalter, writing out `0.1` instead of `.1` is way to complicated, how can anyone even follow that code... – dogmatic69 Jan 15 '19 at 09:38
-
6There'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}"`. – Dave Halter Jan 17 '19 at 13:19