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

Python(django)如何准确处理货币计算,python,django,floating-point,decimal,currency,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 sel

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

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}”。格式(txn.net)

我担心,如果我有多笔交易,并且我想要得到税额的总和,那么在加法后舍入可能会有所不同

但是如果我将
四舍五入(x,2)
放在
tax\u 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

我们最终得到的是创建一个函数:

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

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

使用该函数是否会对您有帮助?@blakev您的意思是使用getcontext?@blakev还是将localcontext()作为ctx:?