在处理浮点精度时,我偶然发现了一个奇怪的事实。为什么用 "%.f"
格式化时 python 只打印整数部分。我愿意知道这背后的机制
>>> a = float(2.12345)
>>> a
2.12345
>>> print "%.2f" % a
2.12
>>> print "%.1f" % a
2.1
>>> print "%f" % a
2.123450
>>> print "%.f" % a
2 #why?
提前感谢您的解释:)
最佳答案
一直都是这样ever since %
formatting was added back in 1993 ;如果 .
后面没有跟十进制数,则 precision is taken as zero .
这没有记录,但与 printf
一致, Python 的 %
格式的灵感来自于:
(optional)
.
followed by integer number or*
, or neither that specifies precision of the conversion. In the case when*
is used, the precision is specified by an additional argument of type int. If the value of this argument is negative, it is ignored. If neither a number nor*
is used, the precision is taken as zero.
有趣的是,同样受 printf
启发的另一个未记录的功能是您可以使用 *
作为精度,如上所示:
>>> "%6.*f" % (2, 1.234)
' 1.23'
关于小数点后没有整数精度的Python浮点精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36598329/