Format numbers into currency format

str.format()

In Python 2.7 and later, you can use the "format specifier for 1000 delimiters" to separate every 3 digits with a comma. (The number of digits to separate and the delimiter cannot be changed) What’s New in Python 2.7 — Python 2.7ja1 documentation

>>> print "¥{:,d}".format(1000000)
¥1,000,000
>>> print "¥{:,.2f}".format(1000000)
¥1,000,000.00

It can also be used in Jinja2.

>>> import jinja2
>>> print jinja2.Template("{{ '\u00A5{:,d}'.format(num) }}").render(num=1000000)
¥1,000,000

Regular expressions

>>> import re
>>> to_yen = lambda n: "¥" + re.sub("(\d{3}(?=\d))", "\\1,", str(n)[::-1])[::-1]
>>> print to_yen(1000000)
¥1,000,000

List comprehension

>>> to_yen = lambda n: "¥" + ",".join([str(n)[::-1][i:i+3] for i in range(0, len(str(n)), 3)])[::-1]
>>> print to_yen(1000000)
¥1,000,000

locale module

>>> import locale
>>> locale.setlocale(locale.LC_ALL, '')
'ja_JP.UTF-8'
>>> print locale.currency(1000000, grouping=True)
¥1,000,000
>>> print locale.currency(1000000, grouping=True, international=True)
JPY 1,000,000

Changing the locale changes the symbols and delimiters.

>>> locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
'en_US.UTF-8'
>>> print locale.currency(1000000, grouping=True)
$1,000,000.00
>>> locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')
'de_DE.UTF-8'
>>> print locale.currency(1000000, grouping=True)
Eu1.000.000,00
>>> locale.setlocale(locale.LC_ALL, 'fr_FR.UTF-8')
'fr_FR.UTF-8'
>>> print locale.currency(1000000, grouping=True)
1 000 000,00 Eu

reference

str.format()

Regular expressions

List comprehension

locale module

Recommended Posts

Format numbers into currency format
Rename YYYYMMDD format files to serial numbers
Format AWS ALB access log into JSON format