0.01 differecene in django calculations

125 views Asked by At

The below-described issue occurred on Python3 with Django 1.9.4

In my Django project, to calculate discount on the sale_amount I am using the below line of code

discount = round((sale_amount - tax_amount ) * discount_rate,2)

the values for the above variables are as follows

sale_amount,tax_amount, discount_rate = 30.00, 6.75, 0.02000000

Variable values are fetched from Django model object all are of same type i.e decimal.Decimal

The calculated discount in a Django project file based the above lines of code is 0.46

When I am calculating discount using the above-described amounts and formula I am getting value: 0.47 in Django console

I am not able to figure out why there is a 0.01 difference between Django console and project calculation.

1

There are 1 answers

2
Yann G On BEST ANSWER

The result of (30 - 6.75) * 0.02 is 0.465. So we would expect to get 0.47 when rounding. But here seems to be an explanation : round() documentation.

The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.