Python babel 如何取整?
How does Python babel round numbers?
我正在用 Flask framework and I'm currently writing unit tests for it. I'm using the Babel package to format 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, which links to some other pieces of code。但我无法真正弄清楚那里出了什么问题以及为什么它似乎随机向上或向下舍入。有人有什么想法吗?
如果您按照代码执行 apply
,您可以看到对 bankersround
过程的引用,它告诉我们需要知道的内容。 Babel 使用银行家四舍五入法,将 5 舍入到最接近的偶数。因此,.245 和 .235 舍入到 .24,因为 .24 是每个最接近的偶数。高于和低于 5 的值通常四舍五入。
我正在用 Flask framework and I'm currently writing unit tests for it. I'm using the Babel package to format 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, which links to some other pieces of code。但我无法真正弄清楚那里出了什么问题以及为什么它似乎随机向上或向下舍入。有人有什么想法吗?
如果您按照代码执行 apply
,您可以看到对 bankersround
过程的引用,它告诉我们需要知道的内容。 Babel 使用银行家四舍五入法,将 5 舍入到最接近的偶数。因此,.245 和 .235 舍入到 .24,因为 .24 是每个最接近的偶数。高于和低于 5 的值通常四舍五入。