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!
You can do it simply like this, the Python way:
Or using that method:
I personally prefer the first one since it's exactly like in Python.
Formatting and padding works well in the same way.
You could use round it will let you round the number to a given precision usage is:
The first parameter specifies the precision (default is 0), the second the rounding method from which you can choose 3:
I want to highlight Joran Beasley's comment because I find it the best solution:
Original comment:
Indeed,
{{ '{0:0.2f}'.format(100) }}
works fantastically.This is just python string formatting. Given the first argument,
{0}
, format it with the following format0.2f
.