Is there a direct approach to format numbers in jinja2?

Lucas picture Lucas · Oct 1, 2012 · Viewed 54.7k times · Source

I need to format decimal numbers in jinja2.

When I need to format dates, I call the strftime() method in my template, like this:

{{ somedate.strftime('%Y-%m-%d') }}

I wonder if there is a similar approach to do this over numbers.

Thanks in advance!

Answer

Lipis picture Lipis · Oct 1, 2012

You can do it simply like this, the Python way:

{{ '%04d' % 42 }}

{{ 'Number: %d' % variable }}

Or using that method:

{{ '%d' | format(42) }}

I personally prefer the first one since it's exactly like in Python.