【发布时间】:2014-09-18 21:21:39
【问题描述】:
假设我有这个带有计算的模型
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
【问题讨论】:
-
使用decimal module 对您有帮助吗?
-
@blakev 你的意思是使用getcontext吗?
-
@blakev 或
with localcontext() as ctx:?
标签: python django floating-point decimal currency