1

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 ?

cnDenis
  • 131
  • 8
  • try it convert to `str()` – Dmitry Zagorulkin Jan 09 '13 at 13:50
  • EDIT: Ah, you specifically don't want to format each one. Sorry, ignore this comment. Have you seen this: http://stackoverflow.com/questions/11260155/how-to-use-float-filter-to-show-just-two-digits-after-decimal-point – Cartroo Jan 09 '13 at 14:15
  • 1
    Looking through the Jinja code, I'm not sure it's possible - you could use the [round](http://jinja.pocoo.org/docs/templates/#round) filter, but that's another change for each float. I can only suggest writing a [custom filter](http://jinja.pocoo.org/docs/api/#writing-filters), which does something like `return "%.2f" % (value,)`. – Cartroo Jan 09 '13 at 14:23

2 Answers2

1

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.

0

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.

SeanPlusPlus
  • 8,663
  • 18
  • 59
  • 84