What are Decimal and Fraction in Python, and when would you use them instead of float?
Decimal does exact base-10 arithmetic, which suits money. Fraction stores a ratio of two integers and gives exact results for things like 1/3. Both avoid the binary rounding errors of float, at the cost of speed.
Explain it simply
A float stores numbers in binary, and many decimal values, like 0.1, have no exact binary form. For an accounting app that adds up rupees and paise, those tiny errors are unacceptable. Decimal works the way you do on paper, digit by digit in base 10. Fraction keeps the numerator and denominator, so one third stays exactly one third.
Example
from decimal import Decimal
from fractions import Fraction
print(Decimal("0.1") + Decimal("0.2")) # Output: 0.3
print(Fraction(1, 3) + Fraction(1, 6)) # Output: 1/2
print(Decimal("10.25") * 3) # Output: 30.75
print(Decimal(0.1) == Decimal("0.1")) # Output: FalseThe last line is a trap: Decimal(0.1) captures the already-inexact float, so build Decimals from strings.
What to say in the interview
"I use Decimal for money and anywhere exact decimal results matter, always constructed from strings. I use Fraction when I need exact rational arithmetic. Both are slower than float, so for scientific work where tiny error is acceptable, float is fine."
Common mistakes
- Creating
Decimal(0.1)from a float and expecting exactness. - Mixing Decimal and float in one expression; Python raises TypeError.