Mastering Python's decimal Module ๐Ÿ’ฑ

Decimal icon

Mastering Python's decimal Module ๐Ÿ’ฑ

The decimal module enables precise decimal arithmetic without floating-point inaccuracies, essential for financial, scientific, and precise numerical applications.

1. Basic Usage and Creating `Decimal` Objects

from decimal import Decimal

a = Decimal('0.1')
b = Decimal('0.2')
print(a + b)  # 0.3 (accurate result, unlike float)

2. Rounding and Precision with `getcontext`

from decimal import Decimal, getcontext, ROUND_HALF_UP

getcontext().prec = 5  # Set total precision to 5 digits
getcontext().rounding = ROUND_HALF_UP

res = Decimal('1.23456') + Decimal('2.34567')
print(res)  # 3.5802 (applied precision and rounding)

3. Financial Calculations and Monetary Representation

from decimal import Decimal

price = Decimal('19.99')
quantity = Decimal('3')
total = price * quantity
print(f"Total amount: {total}")  # Total amount: 59.97

4. Comparisons and Precise Division

from decimal import Decimal

d1 = Decimal('1') / Decimal('3')
d2 = Decimal('0.33333')
print(d1 == d2)  # False (precision-aware)
print(d1.quantize(Decimal('0.00001')))  # 0.33333

Summary

  • Use Decimal objects for accurate decimal arithmetic.
  • Adjust precision and rounding mode via getcontext().
  • Ideal for financial calculations and accurate monetary representations.
  • Effective for precise comparisons and unit calculations.

Comments

Popular posts from this blog

Mastering Python Generators and yield: Efficient Iteration Explained

Mastering Python Sets: Remove Duplicates and Do More

Python Logging Module: Basics and Best Practices ๐Ÿ“