小数点后没有整数精度的Python浮点精度

标签 python floating-point

在处理浮点精度时,我偶然发现了一个奇怪的事实。为什么用 "%.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/

相关文章:

floating-point - 从 int 转换为 float,可以向上舍入吗?

c - 如何在给定整数和小数位的情况下创建 float ?

c++ - 我如何将 C++ 和 Python 与 SWIG 集成

Python 访问变量

java - 为什么我不能将浮点二维数组从函数返回到主类?

c++ - 在计算 C++ 中两个 float 的差时,y * (1 - x/y) 是否比 y - x 更好?

floating-point - tcl_ precision 的状态如何?

python - pandas - 计算出达到一个 pct 需要多少行

python - 确定 TCP listen() 队列中当前积压的连接数

Python 连接列表