【问题标题】:How does Python babel round numbers?Python babel 如何对数字进行舍入?
【发布时间】:2015-02-11 17:52:34
【问题描述】:

我正在使用Flask framework 构建一个金融网站,目前正在为其编写单元测试。我正在使用Babel packageformat money amounts,我遇到了相当奇怪的舍入行为。我希望在5 的情况下四舍五入,或者至少保持一致。但是看看这个:

>>> from decimal import Decimal
>>> from babel.numbers import format_currency
>>> print format_currency(Decimal('.235'), 'EUR', locale='nl_NL')
€ 0,24
>>> print format_currency(Decimal('.245'), 'EUR', locale='nl_NL')
€ 0,24

为什么会这样,更重要的是;我该如何解决?

ps:我希望.245 向上舍入到.25

[编辑]

我去寻找the source,它链接到some otherof code。但我无法真正弄清楚那里出了什么问题以及为什么它似乎随机向上或向下取整。有人知道吗?

【问题讨论】:

标签: python decimal rounding currency python-babel


【解决方案1】:

如果您按照代码一直到apply,您可以看到对bankersround 过程的引用,它告诉我们需要知道的内容。 Babel 使用的是银行家四舍五入法,它舍入到 5 上最接近的偶数。因此,0.245 和 .235 舍入到 0.24,因为 0.24 是每个最接近的偶数。高于和低于 5 的值正常舍入。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多