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

khelwood
  • 55,782
  • 14
  • 81
  • 108
Dean Christian Armada
  • 6,724
  • 9
  • 67
  • 116
  • 5
    `Decimal(.005)` - you already lost precision by creating the float _before_ you created the Decimal. `Decimal(1000) * Decimal(".005")` -> `Decimal('5.000')` – jonrsharpe Jan 07 '22 at 09:54
  • .005 is a float literal, `decimal.Decimal(0.005)` is `Decimal('0.005000000000000000104083408558608425664715468883514404296875')` but `decimal.Decimal("0.005")` is `Decimal('0.005')` – matt Jan 07 '22 at 09:56

1 Answers1

1

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.

Bharel
  • 23,672
  • 5
  • 40
  • 80