Getting only 1 decimal place

PythonRounding

Python Problem Overview


How do I convert 45.34531 to 45.3?

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

>>> "{:.1f}".format(45.34531)
'45.3'

Or use the builtin round:

>>> round(45.34531, 1)
45.299999999999997

Solution 3 - Python

round(number, 1)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlex GordonView Question on Stackoverflow
Solution 1 - PythonreletView Answer on Stackoverflow
Solution 2 - PythonmikuView Answer on Stackoverflow
Solution 3 - PythonDixonDView Answer on Stackoverflow