打印整数或带有 n 个小数的浮点数
·
问题:打印整数或带有 n 个小数的浮点数
在 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).
和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()
总是return
s 和float
。
更多推荐
所有评论(0)