【问题标题】:Rounding down a number to nearest 1000 in Django template在 Django 模板中将数字四舍五入到最接近的 1000
【发布时间】:2019-02-28 00:47:41
【问题描述】:

我想在 Django 模板中将一个数字向下舍入到最接近的 1000。

类似

{{ 123456 | round(1000) }}

123000

在 Django 中有没有内置的方法可以做到这一点,还是我应该只写一个自定义模板标签?

【问题讨论】:

标签: python django templates django-templates


【解决方案1】:

我在Built-in template tags and filters in the Django documentation 中找不到这样的功能。最接近的是floatformat [Django-doc],但我们只能四舍五入到整数(不能以千为单位等)。

编写自定义模板过滤器并不难:

# 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

或者如果您打算只使用整数:

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

然后我们可以使用以下格式对其进行格式化:

{% load rounding %}

{{ 123456|round_down:"1000" }}

然后生成:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    • 2013-08-31
    相关资源
    最近更新 更多