[Fixed]-Convert negative number to positive number in django template?

12👍

I would like to suggest installing django-mathfilters.

Then you can simply use the abs filter like this:

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

8👍

If you don’t want/can’t install django-mathfilters

You can make a custom filter quite easily:

from django import template
register = template.Library()


@register.filter(name='abs')
def abs_filter(value):
    return abs(value)
👤Marcs

7👍

This works without adding django-mathfilters but it’s not a very good practice.

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

Widthratio is meant for creating bar charts but can be used for multiplication

4👍

from this SO:

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

Leave a comment