You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用django-currencies模板标签保留3位小数而非2位?

解决django-currencies模板标签保留3位小数的问题

{% change_currency %}返回的是格式化后的字符串,不是原始浮点数值,所以直接加|floatformat:"3"不会生效——过滤器只对数值类型起作用。给你几个可行的方案:

方案1:修改库的全局配置(推荐)

django-currencies支持全局配置小数位数,在项目的settings.py里添加:

CURRENCIES_DECIMAL_PLACES = 3

这样所有{% change_currency %}标签都会默认返回3位小数的结果,不需要改模板代码。

方案2:自定义模板过滤器转格式

如果不想全局修改,就自己写个过滤器,把转换后的字符串转成数值再格式化:

  1. 在你的app下创建templatetags文件夹,新建custom_filters.py:
from django import template

register = template.Library()

@register.filter
def format_3_decimals(value):
    # 先去掉可能的货币符号,转成浮点数再格式化
    try:
        # 提取字符串中的数字和小数点部分
        num = float(''.join(filter(lambda x: x.isdigit() or x == '.', value)))
        return "{:.3f}".format(num)
    except (ValueError, TypeError):
        return value  # 转换失败就返回原内容
  1. 在模板里先加载自定义过滤器,再使用:
{% load custom_filters %}
{% change_currency video.price CURRENCY.code as converted_price %}
{{ converted_price|format_3_decimals }}

方案3:在视图层提前处理

在视图里先调用django-currencies的Python API完成转换,再格式化后传给模板:

from django_currencies import convert

def your_view(request):
    # ... 其他业务逻辑
    converted_price = convert(video.price, CURRENCY.code)
    formatted_price = "{:.3f}".format(converted_price)
    return render(request, 'your_template.html', {'formatted_price': formatted_price})

模板里直接用{{ formatted_price }}即可。

内容的提问来源于stack exchange,提问作者Panos Ker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 06:02:34