Reputation: 131
I am using Jinja in Flask, I want to make all float looks like 123.45
by default in all my html page, not to keep too many digits after decimal point. I don't want to format every float one by one in the template file. How can I do it ?
Upvotes: 1
Views: 1751
Reputation: 79
you can using context processor for create custome filter for this.
i have copy from flask official documentation for doing this problem.
@app.context_processor
def utility_processor():
def format_price(amount):
return u'{0:.2f}{1}'.format(amount)
return dict(format_price=format_price)
You can pass all value using this filter with
{{ format_price(0.33) }}
hopefully answer.
Upvotes: 1
Reputation: 9033
you could also look into using the decimal module:
http://docs.python.org/2/library/decimal.html
here's a quick example taken from the above docs:
>>> from decimal import *
>>> getcontext().prec = 2
>>> rounded_num = Decimal(1) / Decimal(7)
>>> rounded_num
Decimal('0.14')
by using this module all of the floats in your application will be nicely cast to two digits after the decimal.
Upvotes: 0