Skip to content
Advertisement

How does Python babel round numbers?

I’m building a financial website with the Flask framework and I’m currently writing unit tests for it. I’m using the Babel package to format money amounts and I hit upon rather strange rounding behaviour. I would expect rounding to be up in case of a 5, or to at least be consistent. But look at this:

>>> 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

Why is this so, and more importantly; how can I solve this?

ps: I would prefer .245 to be rounded up to .25

[EDIT]

I went looking for the source, which links to some other pieces of code. But I can’t really figure out what’s wrong there and why it seems to randomly round up or down. Anybody any idea?

Advertisement

Answer

If you follow the code through to apply you can see a reference to a bankersround procedure, which tells us what we need to know. Babel is using the bankers round method of rounding, which rounds to the nearest even number on 5. So, .245 and .235 round to .24 as .24 is the closest even value for each. Values above and below 5 round normally.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement