Python 格式字符串舍入不一致
在Python中,我使用一个格式字符串来使用逗号分隔符和四舍五入。但四舍五入并不一致。比如说Python 格式字符串舍入不一致,python,format,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
>>> '{:,.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将通过增加整数值进行舍入,而奇数则相反
有人能帮我对所有数字进行一致的四舍五入吗?浮点数可能有点不同,不可预测,例如1.5可能是1.499999或1.5000001。因此,对于0.5夏普值,不能期望得到相同的结果 在这种情况下,它有很多解决方法,比如向它添加一个小的数字,比如0.0001,实际上,
.format()
是一致的四舍五入-只是不是您可能期望的方式
定义了两种不同的四舍五入到最接近的数字的方法。您希望它从零开始:
另一种方法是四舍五入到偶数:
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
另请参见如何使用选择自己的舍入行为。还有一点麻烦,但是你可以先手动
round
:格式(round(2.5),,.0f')
给出'3
'。这些值的表示方式可能与你期望的方式不“一致”。这里讨论的很多方法都有帮助。尽管它们中的大多数需要使用除您已经使用的“格式”之外的其他功能-
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