Currency Formatting in Python

Currency formatting in Python

See the locale module.

This does currency (and date) formatting.

>>> import locale
>>> locale.setlocale( locale.LC_ALL, '' )
'English_United States.1252'
>>> locale.currency( 188518982.18 )
'$188518982.18'
>>> locale.currency( 188518982.18, grouping=True )
'$188,518,982.18'

Format numbers as currency in Python

babel.numbers

In [22]: from babel.numbers import format_decimal
In [23]: format_decimal(12345, locale='de_DE')
Out[23]: u'12.345'

In [24]: format_decimal(1.2345, locale='sv_SE')
Out[24]: u'1,234'

Or in your case format_currency:

In [7]: from babel.numbers import format_currency

In [8]: print format_currency(1099.98, 'USD', locale='en_US')
$1,099.98

In [9]: print format_currency(1099.98, 'USD', locale='es_CO')
1.099,98 US$

In [10]: print format_currency(1099.98, 'EUR', locale='de_DE')
1.099,98 €

Python - Formatting items in a list of numbers to be strings with currency symbol

Assuming you want the output as strings:

In [123]: lst = [200,4002,4555,7533]

In [124]: [f'${cur:,}' for cur in lst]
Out[124]: ['$200', '$4,002', '$4,555', '$7,533']

Also don't name your variables as some built-in.

Python string with currency formatted

As an alternative to Haifeng's answer, you could do the following

from decimal import Decimal

str(round(Decimal(row[0]), 2))

Edit: I would also like to add that there is a locale module and that it is probably a better solution, even if it is a little bit more work. You can see how to use it at this question here: Currency formatting in Python



Related Topics



Leave a reply



Submit