Is there a direct approach to format numbers in jinja2?

Question:

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!

Asked By: Lucas

||

Answers:

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.

Answered By: Lipis

You could use round it will let you round the number to a given precision
usage is:

 round(value, precision=0, method='common')

The first parameter specifies the precision (default is 0), the second the rounding method from which you can choose 3:

'common' rounds either up or down
'ceil' always rounds up
'floor' always rounds down
Answered By: Tkingovr

I want to highlight Joran Beasley’s comment because I find it the best solution:

Original comment:

can you not do {{ “{0:0.2f}”.format(my_num) }} or {{ my_num|format “%0.2f” }} (wsgiarea.pocoo.org/jinja/docs/filters.html#format) – Joran Beasley Oct 1 ’12 at 21:07`

Indeed, {{ '{0:0.2f}'.format(100) }} works fantastically.

This is just python string formatting. Given the first argument, {0}, format it with the following format 0.2f.

Formatting and padding works well in the same way.

{{ "{0}".format(size).rjust(15) }}
Answered By: Sandip Bhattacharya

I know the OP says ‘direct’ but after a good hour wasted on this I personally came to this conclusion: ‘direct’ solutions for printing numbers in Jinja2 are either:

  • hard to read (if you don’t code in Python every day all day);
  • or do stuff you may not necessarily want (e.g. drop trailing zeros.)

Ended up with this which is short and gives me code that’s easy to read:

@app.template_filter()
def two_decimals_rounded_up(value):
    """
    Filter to always print with two decimals, rounded up.

    We need this because:
    - The built-in `round` filter provided by Jinja2 will drop trailing zeros.
      e.g. `|round(precision=2, method='ceil')`
    - String formatting in Python is fucking unreadable.

    On rounding up: https://stackoverflow.com/a/9232310/1717535
    """
    return '{0:.2f}'.format(math.ceil(value * 100.0) / 100.0)

And then in the template:

{{ duration|two_decimals_rounded_up }}
Answered By: Fabien Snauwaert
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.