Format numbers as currency in Python

梦想的初衷 提交于 2019-12-03 06:26:56
Padraic Cunningham

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 €

For reference (for those that are looking to format numbers similar to how you would format currency), 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))

Would return

123.456.789,00
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!