Currency formatting in Python Currency formatting in Python python 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'


New in 2.7

>>> '{:20,.2f}'.format(18446744073709551616.0)'18,446,744,073,709,551,616.00'

http://docs.python.org/dev/whatsnew/2.7.html#pep-0378


Not quite sure why it's not mentioned more online (or on this thread), but the Babel package (and Django utilities) from the Edgewall guys is awesome for currency formatting (and lots of other i18n tasks). It's nice because it doesn't suffer from the need to do everything globally like the core Python locale module.

The example the OP gave would simply be:

>>> import babel.numbers>>> import decimal>>> babel.numbers.format_currency( decimal.Decimal( "188518982.18" ), "GBP"188,518,982.18