Python(django)如何准确地处理货币计算

时间:2014-09-18 21:21:39

标签: python django floating-point decimal currency

假设我有这个带有计算的模型

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

1 个答案:

答案 0 :(得分:0)

我们最终要创建一个函数:

def r2(v):
    return Decimal(v).quantize(Decimal('0.00'))

然后使用此函数包装所有与货币相关的计算。