1

Decimal variables in python, is giving different result with arithmetic operations, depending on whether the number was enclosed in quotes when the value was assigned.

>>> x = Decimal(5.36)
>>> y = Decimal(10.56)
>>> x * y
Decimal('56.60160000000000604245542490')

>>> x = Decimal('5.36')
>>> y = Decimal('10.56')
>>> x * y
Decimal('56.6016')

What am I missing here?

Sagar Adhikari
  • 1,312
  • 1
  • 10
  • 17

1 Answers1

2

The input value in the first case is a pair of floats, which by definition are imprecise. See also Is floating point math broken?

In the second case, the strings can be converted directly to the Decimal internal representation, which is precise.

You can verify this for yourself:

>>> x = Decimal(5.36)
>>> print(x)
5.36000000000000031974423109204508364200592041015625
>>> y = Decimal(10.56)
>>> print(y)
10.5600000000000004973799150320701301097869873046875

Demo: https://ideone.com/kieftu

tripleee
  • 175,061
  • 34
  • 275
  • 318