Toivo Mattila
Toivo Mattila

Reputation: 397

Rounding down a number to nearest 1000 in Django template

I want to round a number down to the nearest 1000 in Django template.

Something like

{{ 123456 | round(1000) }}

123000

Is there a built-in way to do this in Django or should I just write a custom template tag?

Upvotes: 1

Views: 894

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

I can not find such function in the Built-in template tags and filters in the Django documentation. The closest is floatformat [Django-doc] but then we can only round to an integer (not on thousands, etc.).

Writing a custom template filter is however not that hard:

# app/templatetags/rounding.py

from django import template
from decimal import Decimal

register = template.Library()

@register.filter
def round_down(value, size=1):
    size = Decimal(size)
    return (Decimal(value)//size) * size

or if you plan to only use integers:

@register.filter
def round_down(value, size=1):
    size = int(size)
    return (value//size) * size

Then we can format it with:

{% load rounding %}

{{ 123456|round_down:"1000" }}

This then generates:

>>> t = """{% load rounding %}{{ 123456|round_down:"1000" }}"""
>>> Template(t).render(Context())
'123000'

Upvotes: 3

Related Questions