Johnny John Boy
Johnny John Boy

Reputation: 3284

How to format a float number in Python Flask and Jinja?

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.

Upvotes: 3

Views: 20633

Answers (2)

atwalsh
atwalsh

Reputation: 3722

Try this:

{{ "£{:,.2f}".format(product_details.UnitPrice) }}

Upvotes: 0

Johnny John Boy
Johnny John Boy

Reputation: 3284

Thanks to Jake who explained

{{'%0.2f'|format(product_details.UnitPrice|float)}}

Is the correct format to get 2 decimal places.

Upvotes: 16

Related Questions