Python decimal.InvalidOperation error

Decimal's initializer can't accept strings with a slash in them. Informally, the string has to look like a single number. This table shows the proper format for string arguments. If you want to calculate 2/3, do

>>> Decimal(2)/Decimal(3)
Decimal('0.6666666666666666666666666667')

Decimal(2/3) gives Decimal('0.66666666666666662965923251249478198587894439697265625') because 2/3 evaluates to a floating point number, and floats have inherently limited precision. That's the closest the computer can get to representing 2/3 using a float.


I solved the problem like this

from decimal import *

b = (Decimal(2) / Decimal(3)).quantize(Decimal(1)/(10**Decimal(30)))

Decimal(b)

quantize allows you to get the necessary accuracy