i'm always getting this error when running something like this:
from decimal import *
getcontext().prec =30
b=("2/3")
Decimal(b)
Error:
Traceback (most recent call last):
File "Test.py", line 6, in <module>
Decimal(b)
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]
Also, why do i get this result from the console?
>>> Decimal(2/3)
Decimal('0.66666666666666662965923251249478198587894439697265625')
Thanks
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With