简体   繁体   English

Django:n 个十进制字段的乘法返回带有 n*2 位小数的结果

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

I'm using django, and I have this model:我正在使用 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')

when I used the property total_sum in the template like {{ line.product.price }} , it return the result 300.0000 .当我在模板中使用属性 total_sum 时,如{{ line.product.price }} ,它返回结果300.0000 even when I tried with the filter tag floatformat like {{ line.product.price|floatformat:2 }} it returned the same value, it didn't format it.即使我尝试使用过滤器标签 floatformat 像{{ line.product.price|floatformat:2 }}它返回相同的值,它没有格式化它。

so I went to the python shell and tried it, and it returned the same value:所以我去了python shell并尝试了它,它返回了相同的值:

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

and when I changed the property to:当我将属性更改为:

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

and tested it in the console:并在控制台中对其进行了测试:

cartline.total_sum
Decimal('900.000000')

it's like concatinating the decimal places... how can I fix that or work around that to limit the display to 2 decimal places when I do the multiplication or any other operation?这就像连接小数位......当我进行乘法或任何其他操作时,我如何解决这个问题或解决这个问题以将显示限制为2个小数位?

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

You can use the round() function to make the total_sum display the exact decimal places you want.您可以使用round()函数使total_sum显示您想要的精确小数位。

Something like this:像这样的东西:

@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