This guide explains Decimal Numbers vs Binary Floating Point through a focused example and practical reasoning. No prior knowledge of this specific operation is required.
Understanding the Concept
The decimal.Decimal type can represent decimal fractions exactly when constructed from strings. Binary float is faster and suitable for many scientific measurements, but its representation is often not exact in base ten.
When You Would Use This
Compare adding decimal currency-style values using the two representations.
Step-by-Step Example
from decimal import Decimal
print(0.1 + 0.2 == 0.3)
first_amount = Decimal("0.1")
second_amount = Decimal("0.2")
print(first_amount + second_amount == Decimal("0.3"))
How the Example Works
The float comparison is false because of binary approximation. The Decimal comparison is true because string-based decimal construction preserves these decimal values exactly.
Example Output
False
True
Try It Yourself
Multiply Decimal("0.19") by three and compare to an equivalent float calculation.
Common Beginner Mistakes
- Building
Decimaldirectly from an existing approximate float and expecting the approximation to disappear. - Mixing
Decimalandfloatvalues without an explicit conversion strategy. - Assuming every financial calculation can ignore required rounding policies.
Key Takeaways
- The
decimal.Decimaltype can represent decimal fractions exactly when constructed from strings. - The float comparison is false because of binary approximation.
- Avoid this mistake: Building
Decimaldirectly from an existing approximate float and expecting the approximation to disappear.