在Python中,当后一种情况需要我将打印输出限制为一定数量的数字时,如何打印可能是整数或实数类型的数字?
长话短说,假设我们有以下示例:
print("{0:.3f}".format(num)) # I cannot do print("{}".format(num))
# because I don't want all the decimals
是否有一种“Pythy”方式来确保例如以防万一num == 1
我打印的1
代替1.000
(我的意思是除了让我的代码变得混乱之外if
声明)
对于 Python 3*,您只需使用round()因为除了四舍五入之外float
s,当应用于整数时,它总是返回一个int
:
>>> num = 1.2345
>>> round(num,3)
1.234
>>> num = 1
>>> round(num,3)
1
此行为记录在help(float.__round__)
:
Help on method_descriptor:
__round__(...)
Return the Integral closest to x, rounding half toward even.
When an argument is passed, work like built-in round(x, ndigits).
And help(int.__round__)
:
Help on method_descriptor:
__round__(...)
Rounding an Integral returns itself.
Rounding with an ndigits argument also returns an integer.
* 使用Python 2,round()
always return
s a float
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)