Decimal numbers in Python are displayed as floats
Question:
I have defined my variables as decimal but they are still output as float when I print them.
My actual problem has complex calculations and I want to print the values to verify my results but I’m getting floats not decimals.
Does this simply not matter as the calculations will come out correctly?
from decimal import Decimal
from decimal import getcontext
getcontext().prec = 6
a=Decimal(0.4)
print(a)
b=Decimal(0.3)
print(b)
x=(a/b)
print("x="+str(x))
Output
0.40000000000000002220446049250313080847263336181640625
0.299999999999999988897769753748434595763683319091796875
x=1.33333
** Process exited - Return Code: 0 **
Press Enter to exit terminal
Update
This makes for some pretty silly looking code.
from decimal import Decimal
from decimal import getcontext
from random import random
getcontext().prec = 6
a=Decimal(str(random()))
print(a)
b=Decimal(str(random()))
print(b)
x=(a/b)
print("x="+str(x))
Result
I still didn’t get the precision as I was expecting but I can work with that 🙂
0.27010708573406494
0.9726705675299723
x=0.277696
** Process exited – Return Code: 0 **
Press Enter to exit terminal
Answers:
can’t exactly figure out what’s causing this issue, but wrapping the decimals around quotes solved it for me:
a=Decimal("0.4")
print(a)
b=Decimal("0.3")
print(b)
x=(a/b)
print("x="+str(x))
Edit: It’s probably because the decimals are being initialized with the float values instead
I have defined my variables as decimal but they are still output as float when I print them.
My actual problem has complex calculations and I want to print the values to verify my results but I’m getting floats not decimals.
Does this simply not matter as the calculations will come out correctly?
from decimal import Decimal
from decimal import getcontext
getcontext().prec = 6
a=Decimal(0.4)
print(a)
b=Decimal(0.3)
print(b)
x=(a/b)
print("x="+str(x))
Output
0.40000000000000002220446049250313080847263336181640625
0.299999999999999988897769753748434595763683319091796875
x=1.33333
** Process exited - Return Code: 0 **
Press Enter to exit terminal
Update
This makes for some pretty silly looking code.
from decimal import Decimal
from decimal import getcontext
from random import random
getcontext().prec = 6
a=Decimal(str(random()))
print(a)
b=Decimal(str(random()))
print(b)
x=(a/b)
print("x="+str(x))
Result
I still didn’t get the precision as I was expecting but I can work with that 🙂
0.27010708573406494
0.9726705675299723
x=0.277696
** Process exited – Return Code: 0 **
Press Enter to exit terminal
can’t exactly figure out what’s causing this issue, but wrapping the decimals around quotes solved it for me:
a=Decimal("0.4")
print(a)
b=Decimal("0.3")
print(b)
x=(a/b)
print("x="+str(x))
Edit: It’s probably because the decimals are being initialized with the float values instead