Decimal Module: Precise Decimal Arithmetic
TL;DR
The decimal module provides exact decimal arithmetic without floating-point precision errors, essential for financial calculations, scientific computing, and any application requiring precise decimal representation.
Interesting!
Floating-point arithmetic can produce surprising results like 0.1 + 0.2 != 0.3
, but decimal arithmetic works exactly like the arithmetic you learned in school with perfect decimal precision.
Basic Decimal Usage
Creating Decimals
python code snippet start
from decimal import Decimal
# Always use strings to avoid float conversion
price = Decimal('19.99')
tax_rate = Decimal('0.08')
# Calculate exact tax
tax = price * tax_rate
total = price + tax
print(f"Total: ${total}") # Total: $21.5892
python code snippet end
Avoiding Float Problems
python code snippet start
# Float precision issues
print(0.1 + 0.2) # 0.30000000000000004
# Decimal precision
print(Decimal('0.1') + Decimal('0.2')) # 0.3
python code snippet end
Precision Control
Setting Global Precision
python code snippet start
from decimal import getcontext
# Set precision to 4 decimal places
getcontext().prec = 4
result = Decimal('1') / Decimal('3')
print(result) # 0.3333
# Financial precision (2 decimal places)
getcontext().prec = 2
money = Decimal('100') / Decimal('3')
print(money) # 33
python code snippet end
Rounding Control
python code snippet start
from decimal import ROUND_HALF_UP, ROUND_DOWN
getcontext().rounding = ROUND_HALF_UP
value = Decimal('2.675').quantize(Decimal('0.01'))
print(value) # 2.68
python code snippet end
Financial Calculations
python code snippet start
from decimal import Decimal, ROUND_HALF_UP
def calculate_compound_interest(principal, rate, time):
"""Calculate compound interest with exact precision"""
p = Decimal(str(principal))
r = Decimal(str(rate))
t = Decimal(str(time))
amount = p * (1 + r) ** t
return amount.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
final_amount = calculate_compound_interest(1000, 0.05, 10)
print(f"Final amount: ${final_amount}") # Exact to the cent
python code snippet end
When to Use Decimal
- Financial applications: Money calculations, accounting
- Scientific computing: High-precision measurements
- Exact decimal representation: When 0.1 must equal 0.1
- Regulatory compliance: Banking, tax calculations
Note: Decimal arithmetic is slower than float arithmetic, so use it when precision matters more than speed. Decimal works seamlessly with statistical calculations for exact results and database storage for financial data. For string formatting, use f-strings and JSON serialization with custom encoders.
Reference: Python Decimal Documentation