How to format a float number in Python Flask and Jinja?
11,414
Thanks to Jake who explained
{{'%0.2f'|format(product_details.UnitPrice|float)}}
Is the correct format to get 2 decimal places.
Author by
Johnny John Boy
Updated on June 13, 2022Comments
-
Johnny John Boy almost 2 years
I've Googled and searched here but can't find an explanation I understand. I've got a value which gets passed into the html template with the value 53.0 which is obtained from a 3rd party API.
My code is:
£{{product_details.UnitPrice}}
Which displays £53.0, is there a way of formatting this as a 2 decimal place float so it correctly reads £53.00.
I have tried reading some instructions here from the github but I don't understand them. I'm trying to avoid formatting each variable separately in my actual Python code or is that the wrong approach?
I'm editing the question because the per my comment:
£{{product_details.UnitPrice|float}}
Didn't make any difference and I don't understand the link given.
-
Jake Conway over 6 yearsTake a look at this answer: stackoverflow.com/a/11260267/7090605
-
Johnny John Boy over 6 yearsI've already read that and it doesn't make sense for my context. £{{product_details.UnitPrice|float}} makes no difference.
-
Jake Conway over 6 yearsTake a look at the specific answer I linked - it mentioned doing this instead:
{{'%0.2f'| format(proc_err|float)}}%
. In the context of this question, it would look like£{{'%0.2f'|format(product_details.UnitPrice|float)}}
. -
Johnny John Boy over 6 yearsThank you Jake, that does solve the problem but doesn't help me understand what's happening here or other possible options. In the github it says "The format filter as implemented in jinja2 is redundant anyway. If I could, I would deprecate and finally remove it, but mitsuhiko would not let me break backwards compatibility. Whenever I have to format a string in a template, I use the modulo operator inline." I don't understand the correct way of doing this.
-
Jake Conway over 6 yearsIt looks like the way to use the modulo operator inline would be something like this:
£{{'%0.2f' % product_details.UnitPrice}}
.
-