LoginSignup
13
16

More than 5 years have passed since last update.

数値を通貨形式へフォーマットする

Last updated at Posted at 2015-04-14

str.format()

Python 2.7以降では「1000区切りのための書式指定子」を使って3桁毎にカンマで区切る事ができる。(区切る桁数や区切り文字の変更はできない)
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

Jinja2の中でも使うことができる。

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

正規表現

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

リスト内包表記

>>> 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モジュール

>>> 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

localeを変更するとシンボルや区切り文字が変更される。

>>> 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

参考

str.format()

正規表現

リスト内包表記

localeモジュール

13
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
16