Jinja Templates - Format a float as comma-separated currency

I'm trying to format a float as comma-separated currency. E.g. 543921.9354 becomes $543,921.94. I'm using the format filter in Jinja templates, which seems to mimic the % operator in Python rather than the Python format function?

How can I accomplish this formatting in Jinja? Is it possible using the format filter? This is what I have so far, which accomplishes everything except the commas:

"$%.2f"|format(543921.9354)

which of course yields

$543921.94


Solution 1:

Update: Using Jinja2 and Python 3, this worked quite nicely in the template without having to define any custom code:

{{ "${:,.2f}".format(543921.9354) }}

I'm not sure exactly what the dependencies are to have this work, but IMHO anyone else reading this answer would do well to at least try it before worrying about custom filters.

Solution 2:

Write a custom filter for that. If you are using python 2.7, it can look like this:

def format_currency(value):
    return "${:,.2f}".format(value)

Solution 3:

Python3.6:

def numberFormat(value):
    return format(int(value), ',d')

Flask global filter

@app.template_filter()
def numberFormat(value):
    return format(int(value), ',d')

Flask global filter for Blueprint

@app.app_template_filter()
def numberFormat(value):
    return format(int(value), ',d')

Call this global filter

{{ '1234567' | numberFormat }}
#prints 1,234,567

Calling it in Jinja without assigning a global filter

{{ format('1234567', ',d') }}
#prints 1,234,567