Kyle Johnson
Kyle Johnson

Reputation: 1675

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

Upvotes: 60

Views: 59506

Answers (6)

seaders
seaders

Reputation: 4096

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'

Upvotes: 7

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

Upvotes: 3

Yongju Lee
Yongju Lee

Reputation: 251

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

Upvotes: 15

biomiker
biomiker

Reputation: 3306

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.

Upvotes: 110

OozeMeister
OozeMeister

Reputation: 4869

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().

Upvotes: 3

alex vasi
alex vasi

Reputation: 5344

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)

Upvotes: 56

Related Questions