【问题标题】:Python (django) how to deal with money calculations accuratelyPython(django)如何准确处理金钱计算
【发布时间】: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


【解决方案1】:

我们最终拥有的是创建一个函数:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-12
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 2013-11-20
    • 2013-07-26
    • 2022-11-17
    相关资源
    最近更新 更多