How do I make Babel use minus signs?

Question:

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.

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

Asked By: leo

||

Answers:

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))
Answered By: stfxc
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.