Order of Operations Django Templates

Tags: , , ,



I have a float variable mynumber in Django templates, and I need to round it to the nearest integer without third party filters, so I’m following this logic:

int(mynumber - 0.5) + 1

In Django templates I can do this:

{{ mynumber|add:"-0.5"|add:"1" }}

But the problem, as you can see, is that there is no order of operations, so I get a different number than the expected, how can I solve this? I haven’t found a way of putting parenthesis, and also I need to convert to integer after the first operation.

Answer

But the problem, as you can see, is that there is no order of operations.

The problem is that you never call int somewhere. The add template filter is implemented as [GitHub]:

@register.filter(is_safe=False) def add(value, arg):
    """Add the arg to the value."""
    try:
        return int(value) + int(arg)
    except (ValueError, TypeError):
        try:
            return value + arg
        except Exception:
            return ''

So it will first cast int on both the value and the operand, and since 0.5 can not be converted to an int, it will return the empty string.

and I need to round it to the nearest integer without third party filters.

The good news is, there is a built-in template filter to do exactly that: |floatformat [Django-doc]. As the documentation says:

If used with a numeric integer argument, floatformat rounds a number to that many decimal places. (…) Particularly useful is passing 0 (zero) as the argument which will round the float to the nearest integer.

So you can render this with:

{{ mynumber|floatformat:"0" }}


Source: stackoverflow