Jinja Templates - Format a float as comma-separated currency

PythonFlaskJinja2

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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

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

#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

Solution 4 - Python

To extend @alex vasi's answer, I would definitely write a custom filter, but I'd also use python's own locale functionality, which handles currency grouping, and the symbol,

def format_currency(value):
    return locale.currency(value, symbol=True, grouping=True)

The main thing to take note of using locale is that it doesn't work with the default 'C' locale, so you have to set it so something that's available on your machine.

For what you're looking for, you probably need,

locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')

but if you wanted sterling pounds, you'd use,

locale.setlocale(locale.LC_ALL, 'en_GB.UTF_8')

.

import locale
locale.setlocale(locale.LC_ALL, 'en_US')
locale.currency(543921.94, symbol=True, grouping=True)
> '$543,921.94'
locale.setlocale(locale.LC_ALL, 'en_GB')
> '£543,921.94'

Solution 5 - Python

If you have Python 2.6 or newer:

You could write a custom filter for one purpose, but, as a broader solution, you could also update the format filter itself:

from jinja import Environment, FileSystemLoader

def format(fmt_str, *args, **kwargs):
    if args and kwargs:
        raise jinja2.exceptions.FilterArgumentError(
            "can't handle positional and keyword "
            "arguments at the same time"
        )
    ufmt_str = jinja2.utils.soft_unicode(fmt_str)
    if kwargs:
        return ufmt_str.format(**kwargs)
    return ufmt_str.format(*args)


env = Environment(loader=FileSystemLoader('./my/template/dir'))
env.filters.update({
    'format': format,
})

This will replace the existing format filter (as of Jinja 2.7.1). The majority of the function was ripped straight from the format source. The only difference between this function and jinja's is that it uses the str.format() function to format the string.

Seeing that Jinja2 (at the time of this writing) no longer supports Python 2.5, I bet it won't be long before the format filter uses Python's str.format().

Solution 6 - Python

Custom Filter using Babel (Can be used to format other currencies as well)

Install Babel (http://babel.pocoo.org/en/latest/api/numbers.html)

pip install Babel

Custom Jinja Filter

from babel.numbers import format_currency

@app.template_filter()
def usdollar(value):
   return format_currency(value, 'USD', locale='en_US')

app.jinja_env.filters['usdollar'] = usdollar

Usage in Jinja Template:

{{ '-10000.500' | usdollar }}

Output : -$10,000.50

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKyle JohnsonView Question on Stackoverflow
Solution 1 - PythonbiomikerView Answer on Stackoverflow
Solution 2 - Pythonalex vasiView Answer on Stackoverflow
Solution 3 - PythonYongju LeeView Answer on Stackoverflow
Solution 4 - PythonseadersView Answer on Stackoverflow
Solution 5 - PythonOozeMeisterView Answer on Stackoverflow
Solution 6 - PythonRavishankar SivasubramaniamView Answer on Stackoverflow