为什么floatformat:2在百位后加逗号

0 投票
2 回答
57 浏览
提问于 2025-04-14 18:27

我有一个Django项目,在我的HTML里有一个{{account.current_balance}}的标签。我还加上了数据类型,以防万一有用。我理解了第1和第2点,但我不明白为什么在第3点中,添加intcomma会在百位数后面加一个逗号。

  1. 没有使用floatformat或intcomma的标签

    {{ account.current_balance }}

输出结果:
当前余额 - 类型
303.6000000000000 - 小数

  1. 使用floatformat:2的标签

    {{ account.current_balance|floatformat:2 }}

输出结果:
当前余额 - 类型
303.60 - 小数

  1. 使用floatformat:2和intcomma的标签

    {{ account.current_balance|floatformat:2|intcomma }}

输出结果:
当前余额 - 类型
,303.60 - 小数
添加models.py和views.py

class BankAccount(models.Model):
    beginning_balance = models.DecimalField(max_digits=10, decimal_places=2)

class Transaction(models.Model):
    amount = models.DecimalField(max_digits=10, decimal_places=2)
    transaction_date = models.DateField()

class UserHome(LoginRequiredMixin, AccountContextMixin, ListView):
    model = Transaction
    template_name = 'base_app/home.html'
    context_object_name = 'transactions'
    paginate_by = 20

    def get_queryset(self):
        user = self.request.user
        return self.model.objects.filter(user=user).filter(status="Posted").order_by('-transaction_date')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        
        total_balance = 0
        
        home_get_accounts = BankAccount.objects.filter(in_report='Yes')
        for account in home_get_accounts:
            posted_transactions_sum = Transaction.objects.filter(bank_account=account, status='Posted').aggregate(total=models.Sum('amount'))['total'] or 0
            current_balance = posted_transactions_sum + account.beginning_balance
            account.current_balance = current_balance  # Adding current_balance attribute to account instance

            total_balance += current_balance
            
            print(type(total_balance))
    
        context['home_get_accounts'] = home_get_accounts #for Beginning Balances
        context['total_balance'] = total_balance
        context['total_balance_type'] = type(total_balance).__name__
        return context

2 个回答

0

在Django模板中使用intcomma过滤器和floatformat过滤器时,intcomma过滤器是用来给大数字加上逗号,以便更容易阅读,但它似乎也影响了数字的小数部分。

没有使用floatformat或intcomma的标签

{{ account.current_balance }}

这只是简单地输出当前的余额,没有任何格式处理。

使用floatformat的标签

{{ account.current_balance|floatformat:2 }}

这会使用floatformat过滤器,把数字四舍五入到小数点后两位。

使用floatformat:2和intcomma的标签:

{{ account.current_balance|floatformat:2|intcomma }}

这同时使用了floatformat和intcomma过滤器。floatformat过滤器把数字四舍五入到小数点后两位,然后intcomma过滤器在数字的整数部分加上逗号。

3

这是Django中的一个错误,具体情况可以查看问题 #35172。这个问题在长期支持的版本中,3.2.25及以上版本和4.2.11及以上版本已经解决了。在当前的主要版本中,从5.0.3版本开始也已经修复了这个问题。

要解决这个问题,最简单的方法就是升级到一个已经修复了这个错误的Django版本。

撰写回答