157

How do I convert 45.34531 to 45.3?

0

3 Answers 3

253

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 
Sign up to request clarification or add additional context in comments.

3 Comments

Is there any chance that your 1st and 3rd solution gives different results? I think they both are exactly same @relet
Try number=-2.55. They also return different types.
@DeveshSaini try number 2.36. 1st will give 2.4, 3nd will give 2.3
44
>>> "{:.1f}".format(45.34531) '45.3' 

Or use the builtin round:

>>> round(45.34531, 1) 45.299999999999997 

4 Comments

Update: Round gives me 45.3 nowdays.
This is answer is correct but the formatting is way to complicated IMO. You should just write "{:.1f}".format(45.34531).
@DaveHalter, writing out 0.1 instead of .1 is way to complicated, how can anyone even follow that code...
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}".
22
round(number, 1) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.