简体   繁体   English

在django模板中将负数转换为正数?

[英]Convert negative number to positive number in django template?

How to convert negative number to positive number in django template? 如何在django模板中将负数转换为正数?

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

If balance.amount is negative number, I want to convert it to positive number. 如果balance.amount为负数,我想将其转换为正数。

I would like to suggest installing django-mathfilters . 我想建议安装django-mathfilters

Then you can simply use the abs filter like this: 然后你可以像这样简单地使用abs过滤器:

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

If you don't want/can't install django-mathfilters 如果你不想/不能安装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 : 这个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. 这可以在不添加django-mathfilters的情况下工作,但这不是一个很好的做法。

{% 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 Widthratio用于创建条形图,但可用于乘法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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