3

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

user2828408
  • 65
  • 1
  • 2
  • 6

1 Answers1

1

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.

Michael M.
  • 10,486
  • 9
  • 18
  • 34
  • 1
    thanks for that input. I thought about doing the same thing, but I was hoping, that this is not a bug in babel (which I assume this is). If nobody comes up with the perfect solution, I will have to use your workaround. – user2828408 Dec 22 '22 at 23:34
  • sure will do. but I hope for a better answer ;.-) – user2828408 Dec 22 '22 at 23:53
  • @user2828408 This does seem like a bug, so I've opened an [issue on GitHub](https://github.com/python-babel/babel/issues/937). – Michael M. Dec 23 '22 at 00:47
  • 1
    You could use a semicolon to separate positive and negative formats like `'¤¤ #,##0.00;¤¤ -#,##0.00'`, so you can do it with only 1 line -- `format_currency(value, 'CHF', '¤¤ #,##0.00;¤¤ -#,##0.00', locale='de_CH')` – DenverCoder1 Dec 27 '22 at 01:10
  • @DenverCoder1 Thanks for the great suggestion! I've edited my question with the update (giving attribution, of course). – Michael M. Dec 27 '22 at 01:15