Is there a direct approach to format numbers in jinja2?

63,466

Solution 1

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.

Solution 2

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.

Solution 3

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

Solution 4

Formatting and padding works well in the same way.

{{ "{0}".format(size).rjust(15) }}
Share:
63,466
Lucas
Author by

Lucas

I have an imaginary friend named Reinaldo

Updated on August 03, 2022

Comments

  • Lucas
    Lucas almost 2 years

    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!

  • Joran Beasley
    Joran Beasley over 11 years
    cept that method of string format is depreciated and should be avoided when possible (I guess ... or something like that...)
  • Joseph White
    Joseph White over 11 years
    @JoranBeasley either case it's not deprecated in the latest version 2.7 on GAE and in the next couple of years I don't see any plans from Google to switch on version 3.0.. It will take some time :)
  • Joran Beasley
    Joran Beasley over 11 years
    I agree I've just gotten flak for using that method instead of the other method ... just mentioning it ... wasnt saying your answer was wrong at all(at least thats not what I meant)...
  • Joseph White
    Joseph White over 11 years
    @JoranBeasley You're right for the new format though.. and I totally hate it :(