【问题标题】:Django: Multiplication of n Decimal Fields returns result with n*2 decimal placesDjango:n个小数字段的乘法返回n * 2个小数位的结果
【发布时间】:2020-10-22 15:21:38
【问题描述】:

我正在使用 django,我有这个模型:

class CartLine(DeletableModel):
product = models.ForeignKey('Product', related_name='cart_lines', on_delete=do_nothing)
cart = models.ForeignKey('Cart', related_name='lines', on_delete=do_nothing)
quantity = models.DecimalField(max_digits=10, decimal_places=2, verbose_name=_('Quantity'))

@property
def total_sum(self):
    return self.product.price * self.quantity

class Meta:
    verbose_name = _('Cart Line')
    verbose_name_plural = _('Cart Lines')

当我在{{ line.product.price }} 这样的模板中使用属性total_sum 时,它返回结果300.0000。即使我尝试使用像{{ line.product.price|floatformat:2 }} 这样的过滤器标签floatformat,它也返回了相同的值,但它没有格式化。

于是我去python shell试了一下,结果还是一样的:

>>> cartline.total_sum
Decimal('300.0000')

当我将属性更改为:

@property
def total_sum(self):
    return self.product.price * self.quantity * self.quantity

并在控制台中对其进行了测试:

cartline.total_sum
Decimal('900.000000')

这就像连接小数位......当我进行乘法或任何其他操作时,如何解决或解决这个问题以将显示限制为 2 个小数位?

【问题讨论】:

  • 精度累加。尝试:total_sum.quantize(Decimal("0.01")) 获得两位精度
  • @schwobaseggl 是的,效果更好,谢谢!

标签: python django decimal


【解决方案1】:

schwobaseggl 评论通过尝试total_sum.quantize(Decimal("0.01")) 解决了我的问题

【讨论】:

    【解决方案2】:

    您可以使用round() 函数使total_sum 显示您想要的精确小数位。

    类似这样的:

    @property
    def total_sum(self):
        return round(Decimal(self.product.price * self.quantity), 2)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多