gpt4 book ai didi

python 2.7字符串格式为十进制作为圆形函数

转载 作者:行者123 更新时间:2023-11-28 18:50:32 24 4
gpt4 key购买 nike

我在字符串格式函数中遇到了一个我不明白的问题。请帮助解释为什么以及如何解决这个问题。谢谢。(python 2.7.3,linux2 上的 [GCC 4.6.3],ubuntu 12.04 x86)

>>> import locale
>>> locale.format("%0.{0}f".format(2), 1.135, grouping=True)
'1.14'
>>> locale.format("%0.{0}f".format(2), 1.125, grouping=True)
'1.12'

>>> ("%0.2f")%(1.135)
'1.14'
>>> ("%0.2f")%(1.125)
'1.12'

我需要格式化结果来匹配 round() 函数

>>> round(1.135, 2)
1.14
>>> round(1.125, 2)
1.13

谢谢大家

最佳答案

这是因为四舍五入不仅仅是将最后一位大于 5 的数字上调,同时截断小于 4 的数字,因为这种方法会导致四舍五入数字的预期平均值增加。

解决方案是使用Bankers' Rounding ,这就是您在这里看到的。

关于python 2.7字符串格式为十进制作为圆形函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13577306/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com