Interview Q&A / Python

IntermediateQuick answer1 min readUpdated 3 Oct 2026

What are Decimal and Fraction in Python, and when would you use them instead of float?

SHORT ANSWER

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

python
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: False

The 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.

#python#data-types#numbers

Related questions

Practise more Python questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Python quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.