Babel formatting error for negative values in currency

Question:

I try to format floats into currency-strings with babel. The following code:

from babel.numbers import format_currency

print(format_currency(value, 'CHF', locale='de_CH'))
print(format_currency(value, 'CHF', '¤¤ #,##0.00', locale='de_CH'))
print(format_currency(value, 'CHF', '#,##0.00', locale='de_CH'))

results in the following formatting errors:

CHF-100.50

-CHF 100.50

-CHF 100.50

I would expect the following result:

CHF -100.50

what am I doing wrong? can’t figure out the error. Thank you very much for all your help

Asked By: user2828408

||

Answers:

I had this issue a while back. I couldn’t find any way to do it with format strings, so I create a small hack-around function:

from babel.numbers import format_currency


def format_currency_fix(val, currency, locale=None):
    return format_currency(val, currency, '¤¤ #,##0.00;¤¤ -#,##0.00',
                           locale=locale)


value = -100.50
print(format_currency_fix(value, 'CHF', locale='de_CH'))  # => CHF -100.50
print(format_currency_fix(value, 'USD', locale='es_CO'))  # => USD -100,50

(Thanks to DenverCoder1 for shortening the code to a one-liner)

You lose a bit of customizability, but it worked for all my use cases.

Answered By: Michael M.