Bypass number rounding
See original GitHub issuebabel.numbers.format_decimal() and babel.numbers.format_currency() have a built-in banker rounding implemented. See: https://github.com/python-babel/babel/blob/3ec7bb104e808d1fda16fbf9fec4b9d7efccaa3f/babel/numbers.py#L648-L649
If we need to localize numbers without rounding, we can’t use these methods.
The minimal default decimal precision per method are:
babel.numbers.format_decimal()=> 3 digits after the dotbabel.numbers.format_currency()=> 2 digits after the dot
Proof:
>>> import babel
>>> set([babel.Locale.parse(l).decimal_formats._data[None].frac_prec
... for l in babel.localedata.locale_identifiers()])
set([(0, 6), (0, 3)])
>>>
>>> import babel
>>> set([babel.Locale.parse(l).currency_formats._data[None].frac_prec
... for l in babel.localedata.locale_identifiers()])
set([(2, 2)])
>>>
So if you have monetary amounts to localize, and they’re already rounded to 2 trailing digits, then you’re lucky. Using any of the format_*() methods will have no side effects.
But for other numbers with higher precision, using format_*() as-is is dangerous. It will introduce unwanted rounding. For example, calling format_currency(0.9999, 'EUR', locale='fr') will return 1,00 €. I expect here to get the pristine 0,9999 € string.
I think there must be a clean and documented way to bypass arbitrary rounding when localizing numbers.
Issue Analytics
- State:
- Created 9 years ago
- Reactions:2
- Comments:14 (13 by maintainers)

Top Related StackOverflow Question
Allright fellows, I think I know how to solve this.
I’ve reached the conclusion that the most versatile solution to this problem is to add a new optional parameter to
format_decimalandformat_currencyto be filled with adecimal.Contextinstance.While remaining backwards compatible, this solution will allow full control on decimal number operations. That means that not only users will be able to change the rounding mode, but also control precision, exponent ranges and so on.
I’ll give it a try this weekend and will submit a pull request.
This issue is addressed by #494.