How to use Python's fractions and decimal modules

· Category: Python Programming

Short answer

Use the decimal module for base-10 decimal arithmetic with configurable precision, and the fractions module to represent numbers as exact ratios of integers.

Details

Floating point numbers (float) use binary representation, which cannot exactly represent values like 0.1. For currency or scientific measurements, Decimal eliminates rounding surprises:

from decimal import Decimal, getcontext
getcontext().prec = 6
result = Decimal('0.1') + Decimal('0.2')  # Exactly 0.3

The fractions.Fraction class stores numbers as numerator/denominator pairs, making it ideal for exact rational arithmetic. When processing numeric data from files or APIs, combine these modules with Python error handling to catch malformed inputs gracefully. You can also transform collections of numeric strings using list comprehensions before converting them to Decimal or Fraction in bulk.

Tips

  • Always construct Decimal from strings, not floats, to preserve exact input values.
  • Use Fraction.limit_denominator() to approximate floats rationally when exactness is not required.
  • Set context precision globally at application startup, or use local contexts for isolated calculations.