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

隐身守侯 提交于 2021-01-05 09:07:59

问题


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.


回答1:


Thanks to Jake who explained

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

Is the correct format to get 2 decimal places.




回答2:


Try this:

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



来源:https://stackoverflow.com/questions/46144767/how-to-format-a-float-number-in-python-flask-and-jinja

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!