Search code examples
pythonpython-3.xpython-decimal

Dividing Decimals in python returns inaccurate results


>>> 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?


Solution

  • 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.