FlaskでJinjaで金額表示(カンマ)にする方法

Jinjaテンプレートで、金額でカンマ区切りで表示させたかった。

ちょっと調べたので、メモ用。

localeが使えそうだった。

>>> import locale
>>> locale.setlocale(locale.LC_NUMERIC, 'ja_JP')
'ja_JP'
>>> amount = 10000
>>> print(locale.format('%d', amount, True))
10,000

Templates — Flask 0.11-dev documentation
にContext Processorsで金額フォーマットをしていたので参考にさせて頂いた。以下抜粋

function

@app.context_processor
def utility_processor():
    def format_price(amount, currency=u''):
        return u'{0:.2f}{1}'.format(amount, currency)
    return dict(format_price=format_price)

templates

{{ format_price(0.33) }}

自分は以下のようにしました。

import locale
locale.setlocale(locale.LC_NUMERIC, 'ja_JP')

@app.context_processor
def utility_processor():
    def format_currency(amount):
        return locale.format('%d', amount, True)
    return dict(format_currency=format_currency)

テンプレート

{{ format_currency(1465100) }}

下記のようの表示されるはず。

1,465,100

はてなブログPythonの記法はないですかね。知ってる方がいたら教えて欲しいですね。

久しぶりにFlaskを触ったな。Flaskは、やっぱり楽しいな。

参考にしたサイト

  1. Templates — Flask 0.11-dev documentation
  2. python - Jinja Templates - Format a float as comma-separated currency - Stack Overflow
  3. Pythonで3桁区切りのカンマ挿入 | #eight