簡體   English   中英

Django:n 個十進制字段的乘法返回帶有 n*2 位小數的結果

[英]Django: Multiplication of n Decimal Fields returns result with n*2 decimal places

我正在使用 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')

當我在模板中使用屬性 total_sum 時,如{{ line.product.price }} ,它返回結果300.0000 即使我嘗試使用過濾器標簽 floatformat 像{{ line.product.price|floatformat:2 }}它返回相同的值,它沒有格式化它。

所以我去了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個小數位?

schwobaseggl評論通過嘗試total_sum.quantize(Decimal("0.01"))解決了我的問題

您可以使用round()函數使total_sum顯示您想要的精確小數位。

像這樣的東西:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM