I’ve understood there’re several questions/answers available with similar headlines for C++, JS, and Java in SO but I’d like to know the right Pythonic way to address the aspect of storing variables, recomputing with another float var, and presenting them. I list the examples below. if there’s a duplicate for Python, please let me know too and I’ll close this. Thank you.
1. First Example
Expecting:
In[1]: a = 0.35 + 0.1
In[2]: print(a)
0.45
Actual:
In[1]: a = 0.35 + 0.1
In[2]: print(a)
0.44999999999999996
My take to present:
format(a, '.2f')
'0.45'
I thought Decimal could help but it looks like the same
In[1]:import decimal
from decimal import Decimal
In[2]:Decimal(0.35) + Decimal(0.1)
Decimal('0.4499999999999999833466546306')
2. Second Example
Expecting:
In[1]:b = 0.35
In[2]:b.as_integer_ratio()
(7, 20)
Actual:
In[1]:b = 0.35
In[2]:b.as_integer_ratio()
(3152519739159347, 9007199254740992)
>Solution :
You are starting with imprecise floats. Start with exact decimals, from string representation:
Decimal("0.35") + Decimal("0.1")
# => Decimal('0.45')
Decimal("0.35").as_integer_ratio()
# => (9, 20)
Or start with exact numbers (e.g. integers):
Decimal(35) / Decimal(100)
# => Decimal('0.35')
from fractions import Fraction
Fraction(35, 100)
# => Fraction(7, 20)