简体   繁体   中英

Convert negative number to positive number in django template?

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.

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 %}

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)

from this SO :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM