148

How do I convert 45.34531 to 45.3?

Georgy
  • 12,464
  • 7
  • 65
  • 73
Alex Gordon
  • 57,446
  • 287
  • 670
  • 1,062

3 Answers3

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
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
    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
  • 6
    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
21
round(number, 1)
DixonD
  • 6,557
  • 5
  • 31
  • 52