gpt4 book ai didi

python - 打印整数或带 n 位小数的 float

转载 作者:太空狗 更新时间:2023-10-29 20:10:25 25 4
gpt4 key购买 nike

在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com