Django 模板中的数字格式

Bok*_*oky 6 python django

我有一本字典如下:

{'warranty': '1 jaar', 'delivery': u'2017-06-13', 'to_pay': 9000.0, 'deposit': 1000.0}
Run Code Online (Sandbox Code Playgroud)

我将它发送到 Django 模板,我想显示to_pay9.000,00. 但我不能。

我有

{% load humanize %}
{% load i18n %}
{% load l10n %}
Run Code Online (Sandbox Code Playgroud)

在模板的顶部,我有

USE_I18N = True
USE_L10N = True
Run Code Online (Sandbox Code Playgroud)

在设置.py

我试过什么:

{{ car.sale.to_pay|floatformat:2|intcomma }} // 9,000,00
{{ car.sale.to_pay|intcomma }} // 9.000,0  almost good, but I need two zeroes after comma
{{ car.sale.to_pay|localize }} // 9000,0
Run Code Online (Sandbox Code Playgroud)

任何的想法?

Bro*_*bin 3

自定义模板过滤器

您始终可以创建自己的模板过滤器以获得所需的结果。这是一个使用 intcomma 将数字格式化为您想要的结果的实现

from django import template
from django.contrib.humanize.templatetags.humanize import intcomma

register = template.Library()

@register.filter
def my_float_format(number, decimal_places=2, decimal=','):
    result = intcomma(number)
    result += decimal if decimal not in result else ''
    while len(result.split(decimal)[1]) != decimal_places:
        result += '0'
    return result
Run Code Online (Sandbox Code Playgroud)

然后在模板中使用

{% load my_tags %}
{{ 450000.0|my_float_format }}
Run Code Online (Sandbox Code Playgroud)

呈现此

450.000,00
Run Code Online (Sandbox Code Playgroud)

旧答案(不正确)

您可以使用stringformat过滤器首先使用基本的Python字符串格式并获取所需的小数位数,然后将其传递intcomma以获取数字格式。

{% load humanize %}

{{ car.sale.to_pay|stringformat:'0.2f'|intcomma }}
Run Code Online (Sandbox Code Playgroud)