15

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

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

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

kangfend
  • 367
  • 4
  • 16

4 Answers4

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 %}
Krystian Cybulski
  • 10,789
  • 12
  • 67
  • 98
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
  • 3,768
  • 5
  • 33
  • 42
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

  • 2
    Oh man! `widthratio` to multiply! Hehe, way to think out of the box -- I love it the strangest of ways. Time for a public service announcement. If you ever do decide to use the above, please please please add `{# widthratio is being used to multiply balance.amount times -1 #}` to make this code have a smidgen of meaning. – Krystian Cybulski Nov 10 '14 at 13:06
  • 1
    Great Work Bro Keep it up – Hassan ALi Feb 06 '19 at 07:33
4

from this SO:

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