Dividing Decimals in python returns inaccurate results

91 Views Asked by At
>>> x = Decimal(1000)
>>> y = Decimal(.005)
>>> x * y
Decimal('5.000000000000000104083408559')

I expected the result to be just 5

>>> a = 1000
>>> b = .005
>>> a * b
5.0

Above is what I expected.

====

The original intention is to divide a DecimalField from Django. Should I convert the Decimal value to float instead? For me to expect accurate resuls?

1

There are 1 best solutions below

0
Bharel On BEST ANSWER

Pass it as a string:

>>> x = Decimal(1000)
>>> y = Decimal(".005")
>>> x * y
Decimal('5.000')

The issue is converting some floats into decimal. Starting with a string wouldn't be an issue.


As for your question: you should do the operations on a Decimal for it to be accurate.