【问题标题】:Number formatting in Django templateDjango模板中的数字格式
【发布时间】:2017-06-13 14:26:21
【问题描述】:

我有一本字典如下:

{'warranty': '1 jaar', 'delivery': u'2017-06-13', 'to_pay': 9000.0, 'deposit': 1000.0}

我将它发送到 Django 模板,我想将 to_pay 显示为 9.000,00。但我不能。

我有

{% load humanize %}
{% load i18n %}
{% load l10n %}

在模板的顶部,我有

USE_I18N = True
USE_L10N = True

在 settings.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

有什么想法吗?

【问题讨论】:

  • 为什么不将字典中的浮点数转换为字符串并根据需要添加零?
  • 例如{k: '{:.2f}'.format(v) if isinstance(v, float) else v for k,v in your_dict.items()} 然后将您的dict数据作为str传递到您的模板中。

标签: python django


【解决方案1】:

自定义模板过滤器

您始终可以创建自己的模板过滤器来获得所需的结果。这是一个使用 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

然后在模板中使用

{% load my_tags %}
{{ 450000.0|my_float_format }}

渲染这个

450.000,00

旧答案(不正确)

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

{% load humanize %}

{{ car.sale.to_pay|stringformat:'0.2f'|intcomma }}

【讨论】:

  • 这样我得到9,000.00 而不是9.000,00
  • 比较接近,哈哈。如果您使用localize 而不是intcomma 会怎样?
  • 然后我得到9000.00 :)
  • @Boky 这可能是因为 docs.djangoproject.com/en/1.11/topics/i18n/formatting 中设置的语言会影响 intcomma 的作用
  • 我想我在上面想出了一个新的解决方案。
猜你喜欢
  • 2010-09-25
  • 2011-12-05
  • 1970-01-01
  • 2011-06-22
  • 2020-06-28
  • 1970-01-01
  • 2022-08-17
  • 2014-10-11
相关资源
最近更新 更多