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



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

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属性中失败,因为它是Decimal减去float,例如

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

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

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

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

最新更新