Converting a negative number to a positive number in a django template?

How to convert a negative number to a positive number in a django template?

{% for balance in balances %} {{ balance.amount }} {% endfor %} 

If balance.amount is a negative number, I want to convert it to a positive number.

+6
source share
4 answers

I would suggest installing django-mathfilters .

Then you can simply use the abs filter as follows:

 {% for balance in balances %} {{ balance.amount|abs }} {% endfor %} 
+5
source

from this SO :

 {% if qty > 0 %} Please, sell {{ qty }} products. {% elif qty < 0 %} Please, buy {{ qty|slice:"1:" }} products. {% endif %} 
+4
source

If you do not want / cannot install django-mathfilters

You can make your own filter pretty easily:

 from django import template register = template.Library() @register.filter(name='abs') def abs_filter(value): return abs(value) 
+3
source

This works without adding django-mathfilters, but this is not a good practice.

 {% if balance.amount < 0 %} {% widthratio balance.amount 1 -1 %} {% else %} {{ balance.amount }} {% endif %} 

Widthratio is for creating histograms, but can be used for multiplication

+1
source

Source: https://habr.com/ru/post/977969/


All Articles