Number format as currency in Python

I am learning about currency formatting in Python , using the locale module to format numbers as a currency. For instance,

#! /usr/bin/env python # -*- coding: utf-8 -*- import locale value = 123456789 l = locale.setlocale(locale.LC_ALL, '') # LC_CTYPE=en_US.UTF-8;LC_NUMERIC=fr_FR.UTF-8;LC_TIME=fr_FR.UTF-8;LC_COLLATE=en_US.UTF-8;LC_MONETARY=fr_FR.UTF-8;LC_MESSAGES=en_US.UTF-8;LC_PAPER=fr_FR.UTF-8;LC_NAME=fr_FR.UTF-8;LC_ADDRESS=fr_FR.UTF-8;LC_TELEPHONE=fr_FR.UTF-8;LC_MEASUREMENT=fr_FR.UTF-8;LC_IDENTIFICATION=fr_FR.UTF-8 s = locale.currency(value, grouping=True) # 123 456 789,00 â‚Ŧ locale.setlocale(locale.LC_ALL, 'en_US.utf-8') s = locale.currency(value, grouping=True) # $123,456,789.00 locale.setlocale(locale.LC_ALL, 'en_US') # WHY? locale.Error: unsupported locale setting s = locale.currency(value, grouping=True) 

I would like to format the numbers in another currency, say de_DE . I ran into the locale.Error: unsupported locale setting problem, because the de_DE locale de_DE not in the locale -a list.

 locale.setlocale(locale.LC_ALL, 'de_DE') # locale.Error: unsupported locale setting s = locale.currency(value, grouping=True) 

One solution is to add this locale to my machine. Is there a better way?

+9
source share
2 answers

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 â‚Ŧ 
+7
source

For reference (for those who want to format numbers similar to currency formatting), you can use locale.format_string to format numbers

 value = 123456789 import locale locale.setlocale(locale.LC_ALL, 'de_DE') print(locale.format_string('%.2f', value, True)) 

Will return

 123.456.789,00 
+2
source

All Articles