格式化字符串舍入不一致

时间:2015-04-16 10:26:14

标签: python format

在Python中,我使用格式字符串来使用逗号分隔符并进行舍入。但四舍五入并不一致。例如

>>> '{:,.0f}'.format(1.5)
'2' # Here it is increasing to next integer
>>> '{:,.0f}'.format(2.5)
'2' # Here it is suppose to give 3 as per the earlier logic.

取决于小数点前的数字。如果它是偶数,则Python通过增加整数值来四舍五入,反之则是奇数。

有人可以帮助我获得所有数字的一致性舍入

2 个答案:

答案 0 :(得分:3)

实际上,.format()一直在四舍五入 - 只是不是你想象的那样。

IEEE floating point standard定义了四种舍入到最近数字的不同方法。你期望它远离零

 2.5    rounds to   3.0
 1.5    rounds to   2.0
 0.5    rounds to   1.0
-0.5    rounds to  -1.0
-1.5    rounds to  -2.0

另一种方法是舍入到偶数:

 2.5    rounds to   2.0
 1.5    rounds to   2.0
 0.5    rounds to   0.0
-0.5    rounds to  -0.0     (yes, this is different from 0)
-1.5    rounds to  -2.0

这种方法是无偏的,因为舍入数的和/平均值更可能与原始数的和/平均值相匹配。这就是为什么IEEE建议将其作为默认规则进行舍入。

舍入的实现因功能,版本而异。这是一个关于不同表达式如何围绕的表格:

x                           2.5     1.5     0.5     -0.5    -1.5
round(x) in Py 2.x  away    3.0     2.0     1.0     -1.0    -2.0
round(x) in Py 3.x  even    2.0     2.0     0.0     -0.0    -2.0    Changed behaviour
'{:.0f}'.format(x)  even    2       2       0       -0      -2
'%.0f' % x          even    2       2       0       -0      -2
numpy.around(x)     even    2.0     2.0     0.0      0.0    -2.0

另请参阅dawg's answer,了解如何使用Decimal module选择自己的舍入行为。并John La Rooy has answered一个similar question

答案 1 :(得分:0)

浮点数可能有点变化,不可预测,例如1.5可能是1.4999999或1.5000001。所以你不能期望.5锐利值的结果相同。

在这种情况下,它有很多方法可以解决,例如像0.0001

那样添加一个小数字
相关问题