简体   繁体   中英

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

I'm using django, and I have this model:

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 . 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.

so I went to the python shell and tried it, and it returned the same value:

>>> 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?

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.

Something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM