Search code examples
djangodjango-templatesjinja2

How to format a number to a decimal in django template?


Hi I am trying to format a number (1999) in Django template to a decimal with 2DP, e.g. (19.99)

<div class="card-body">
                        <p class="card-text">{{ object.max_price|stringformat:".2f" )} {{object.currency.id}}</p>
                        <p class="card-text">{{object.min_price}} {{object.currency.id}}</p>
                        <p class="card-text">-{{object.discount_percentage}}%</p>
                        <p class="card-text">{{object.recommended_retail_price}} {{object.currency.id}}</p>
</div>

I get this error:

TemplateSyntaxError at /products

Could not parse the remainder: ' )} {{object.currency.id' from 'object.max_price|stringformat:".2f" )} {{object.currency.id'

Request Method:     GET
Request URL:    http://localhost:8000/products?page=1
Django Version:     4.0
Exception Type:     TemplateSyntaxError
Exception Value:    

Could not parse the remainder: ' )} {{object.currency.id' from 'object.max_price|stringformat:".2f" )} {{object.currency.id'

I have also tried using floatformat and get a similar error:

TemplateSyntaxError at /products

Could not parse the remainder: ' )} {{object.currency.id' from 'object.max_price|floatformat )} {{object.currency.id'

Request Method:     GET
Request URL:    http://localhost:8000/products?page=1
Django Version:     4.0
Exception Type:     TemplateSyntaxError
Exception Value:    

Could not parse the remainder: ' )} {{object.currency.id' from 'object.max_price|floatformat )} {{object.currency.id'

How is it possible to format an integer in Django jinja template as a decimal to 2DP?


Solution

  • You have used the wrong closing bracket here:

    {{ object.max_price|stringformat:".2f" )}