Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Babel numbers format_currency function

I am working on a site where we use many languages and in order to display the price/currency accordingly we make use of babel library. The issue is when calling the format_currency it returns always the cent part if even if the price is explicitly casted into an integer.

Example:

>>> print format_currency(100, 'EUR', locale='fr_FR')
100,00 €

>>> print format_currency(int(100), 'EUR', locale='fr_FR')
100,00 €

Is it a way around this so that the return value excludes the cent part to have something like

>>> print format_currency(int(100), 'EUR', locale='fr_FR')
100 €
like image 570
Palmer Avatar asked Jan 09 '23 23:01

Palmer


1 Answers

You can specify a custom format:

format_currency(100, 'EUR', format=u'#,##0\xa0¤', locale='fr_FR')

See the LDML markup spec for more details; the \xa0 byte is a U+00A0 NO-BREAK SPACE character; rather than a regular space.

For fr_FR the default is #,##0.00\xa0¤, and the .00 part signals that a decimal portion should be printed with two digits, padded if not present. My example above simply removed the decimal portion, you also could use .## to allow for a fraction if the number is not an exact integer, but note that in that case a .5 value is printed without a 2nd digit!

Demo:

>>> from babel.numbers import format_currency
>>> print format_currency(100, 'EUR', format=u'#,##0\xa0¤', locale='fr_FR')
100 €
>>> print format_currency(100.0, 'EUR', format=u'#,##0.##\xa0¤', locale='fr_FR')
100 €
like image 178
Martijn Pieters Avatar answered Jan 21 '23 15:01

Martijn Pieters