问题描述
在Python中,当后一种情况要求我将打印输出限制为一定数量的数字时,如何打印可能是整数或实数的数字?
In Python, how can one print a number that might be an integer or real type, when the latter case would require me to limit my printout to a certain amount of digits?
长话短说,假设我们有以下示例:
Long story short, say we have the following example:
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
声明)
Is there a "Pythy" way to ensure e.g. in case num == 1
that I print 1
instead of 1.000
(I mean other than cluttering my code with if
statements)
推荐答案
对于Python 3 *,您只需使用 round()
因为除了舍入 float
外,当将其应用于整数时,它始终会返回诠释
:
With Python 3*, you can just use round()
because in addition to rounding float
s, when applied to an integer it will always return an 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
.
* With Python 2, round()
always return
s a float
.
这篇关于打印整数或带有n个小数的浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!