2014-09-18 24 views
0

可以說我有這個模型計算的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屬性中失敗,因爲它的十進制減去浮點數,例如。

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 
+0

會使用[decimal模塊](https://docs.python.org/2/library/decimal.html)幫助你嗎? – blakev 2014-09-18 21:31:14

+0

@blakev你是指使用getcontext? – 2014-09-18 21:35:01

+0

@blakev或'with localcontext()as ctx:'? – 2014-09-18 21:45:23

回答

0

我們最終什麼事已經是創造一個功能:

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

然後包裝所有貨幣相關calulations使用此功能。