Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I make Babel use minus signs?

Why is it that Babel does not use the minus sign used by my locale, in functions like format_decimal()? It seems to me like this would be the very job of a library like Babel.

Is there a way I can enforce the usage of locale specific minus signs?

>>> import babel
>>> babel.__version__
'2.11.0'


>>> from babel.numbers import format_decimal, Locale
>>> l = Locale("sv_SE")
>>> l.number_symbols["minusSign"]
'−'
>>> format_decimal(-1.234, locale=l)
'-1,234'

Despite the fact that Local.number_symbols clearly contain a different character (in this case U+2212), format_decimal() (and other Babel formatting functions) use only the fallback hyphen-minus.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am getting '-1,234' (with an hyphen-minus) where I would have expected '−1,234' (with the U+2212 minus sign).

>Solution :

Babel uses the hyphen-minus (‘-‘) by default, despite the fact that a different character may be specified in the number_symbols attribute of the Locale object.

This is because the format_decimal() function, rely on the locale module of the Python standard library to format numbers. The locale module uses the C library’s localization functions, which are not always capable of handling Unicode characters like the U+2212 MINUS SIGN (minus sign used by your locale).

But you can try this:

from babel.numbers import format_decimal, Locale

l = Locale("sv_SE")

number = -1.234
minus_sign = l.number_symbols["minusSign"]
formatted_number = "{}{:,.5f}".format(minus_sign, abs(number))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading