136

How do I convert 45.34531 to 45.3?

Georgy
  • 9,972
  • 7
  • 57
  • 66
Alex Gordon
  • 54,010
  • 276
  • 644
  • 1,024

3 Answers3

221

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,562
  • 2
  • 31
  • 41
35
>>> "{:.1f}".format(45.34531)
'45.3'

Or use the builtin round:

>>> round(45.34531, 1)
45.299999999999997
miku
  • 172,072
  • 46
  • 300
  • 307
  • 12
    Update: Round gives me 45.3 nowdays. – Nathan Mar 30 '12 at 14:44
  • 2
    This 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
  • 3
    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}"`. – Dave Halter Jan 17 '19 at 13:19
16
round(number, 1)
DixonD
  • 6,317
  • 5
  • 29
  • 51