假设我有这个带有计算的模型
Class Transaction(models.Model):
amount = models.DecimalField(...)
tax = models.DecimalField(...)
@property
def tax_amount(self):
return self.amount * self.tax
@property
def net(self):
return self.amount - self.tax_amount
当我想打印net
我正在使用"{:.2f}".format(txn.net)
我担心如果我有多个交易并且我想获得tax_amount的总和,那么在添加之后舍入可能会有所不同。
但如果我将round(x, 2)
放在tax_amount
属性周围,它将在net
属性中失败,因为它是十进制减去浮点数,例如。
Class Transaction(models.Model):
amount = models.DecimalField(...)
tax = models.DecimalField(...)
@property
def tax_amount(self):
return round(self.amount * self.tax, 2)
@property
def net(self):
# TypeError: unsupported operand type(s) for -: 'float' and 'Decimal'
return self.amount - self.tax_amount
答案 0 :(得分:0)
我们最终要创建一个函数:
def r2(v):
return Decimal(v).quantize(Decimal('0.00'))
然后使用此函数包装所有与货币相关的计算。