jxm*_*s12 2 python decimal-point rounding
其他问题表明,Python f 字符串在某个小数点处对数字进行四舍五入,而不是截断它们。
我可以用下面的例子来展示这一点:
>>> number = 3.1415926
>>> print(f"The number rounded to two decimal places is {number:.2f}")
The number rounded to two decimal places is 3.14
>>>
>>> number2 = 3.14515926
>>> print(f"The number rounded to two decimal places is {number2:.2f}")
The number rounded to two decimal places is 3.15
Run Code Online (Sandbox Code Playgroud)
然而,我遇到了另一种情况,Python 似乎截断了数字:
>>> x = 0.25
>>> f'{x:.1f}'
'0.2'
Run Code Online (Sandbox Code Playgroud)
我本以为0.25,精确到小数点后一位,会四舍五入为0.3。我是否遗漏了什么,或者这种行为不一致?
您所看到的仍然是四舍五入,它只是不是您所期望的四舍五入。默认情况下,Python将关系舍入为 Even,而不是总是向上舍入,因为对关系进行向上舍入会在数据中产生特定偏差(将关系舍入到偶数也是如此,但这些偏差问题较少,因为它们不影响\xe2\x80\x99t总体分布)。
\n举个例子:
\nnums = [1.5, 2.5, 3.5, 4.5]\n[round(x) for x in nums]\n# [2, 2, 4, 4]\nRun Code Online (Sandbox Code Playgroud)\n对于更多的小数点也是如此:
\nnums = [0.25, 0.75]\n[round(x, 1) for x in nums]\n# [0.2, 0.8]\nRun Code Online (Sandbox Code Playgroud)\n在上面的列表中包含0.05, 0.15\xe2\x80\xa6\xc2\xa0 会产生令人惊讶的结果,因为这些十进制浮点值不能精确地表示为二进制浮点值,因此它们\xe2\x80\ x99re 不完全均匀;例如,0.05 存储为大约 0.05000000000000000278\xe2\x80\xa6,因此它不会\xe2\x80\x99 向下舍入到(偶数)0.0,而是向上舍入到(奇数)0.1。