Day 46: Money2 Integration: Using fixed-decimal math to eliminate rounding errors in totals
Day 46: Money2 Integration: Eliminating Floating-Point Errors
In our previous lesson, Day 54: Financial Persistence, we established how to store monetary values in SQLite and Firestore using integer-based subunits (e.g., storing $10.00 as 1000 cents). While this prevents data loss in the database, it creates a "presentation gap": your UI logic remains vulnerable to the classic pitfalls of floating-point math. Today, we bridge that gap by integrating the money2 package, moving away from double and num types entirely to ensure our travel appβs pricing calculations remain deterministic.
The Problem: Why 0.1 + 0.2 != 0.3
In IEEE 754 floating-point arithmeticβthe standard used by double in Dartβmany decimal fractions cannot be represented exactly. They are stored as repeating binary fractions. If you perform tax calculations or currency conversions using double, you will eventually hit a rounding error.
A famous real-world example of this is the Ariane 5 Flight 501 disaster. The European Space Agencyβs rocket self-destructed 37 seconds after launch because a 64-bit floating-point number was converted to a 16-bit signed integer, causing an overflow. While your travel app won't explode, a rounding error in a booking engine that compounds over millions of transactions results in "phantom money"βdiscrepancies that auditors and payment gateways (like Stripe or Adyen) will flag as a failure of system integrity.
The Solution: Fixed-Decimal Arithmetic
To avoid this, we replace floating-point math with fixed-decimal arithmetic. Instead of a binary approximation, we treat money as an object that holds a value and a currency definition.
The Money class from money2 encapsulates the scale (the number of decimal places) and ensures that arithmetic operations (addition, subtraction, multiplication) are performed with integer precision.
Conceptual Implementation
Rather than using double price = 10.99;, we define our prices as:
Keep going with the full lesson
The rest of this lesson β plus its implementation guide, runnable scripts and source code β is included with the course or an All Access plan. Create a free account to start the free lessons in every course.
Already a member? Sign in