Python 只得到 1 个小数位

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3400965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:52:15  来源:igfitidea点击:

Getting only 1 decimal place

pythonrounding

提问by l--''''''---------''''''''''''

How do I convert 45.34531to 45.3?

我如何转换45.3453145.3

采纳答案by relet

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

回答by DixonD

round(number, 1)

回答by miku

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

Or use the builtin round:

或者使用内置回合:

>>> round(45.34531, 1)
45.299999999999997