在 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
之外,当应用于整数时,它总是会返回一个 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()
总是返回
一个float
。
关于python - 打印整数或带 n 位小数的 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42489975/