data
serialization
ai_generated
true
JSON serialized float value 0.1 + 0.2 becomes 0.30000000000000004 causing comparison failures
ID: data/float-precision-json-serialization
85%Fix Rate
90%Confidence
3Evidence
2023-01-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| any | active | — | — | — |
Root Cause
IEEE 754 floats cannot represent 0.1 exactly. JSON serializes the full double representation. Downstream consumers comparing 0.3 != 0.30000000000000004 fail. Financial calculations with floats corrupt data silently.
genericWorkarounds
-
95% success Use Decimal type for monetary values, serialize as string in JSON
from decimal import Decimal; json.dumps({"amount": str(Decimal("0.10") + Decimal("0.20"))}) # "0.30" -
92% success Use integer cents/smallest unit for money (avoid decimals entirely)
Store $1.50 as 150 cents (integer). No float precision issues. Convert to display format only at presentation.
-
82% success Use custom JSON encoder with controlled precision for scientific data
class PrecisionEncoder(json.JSONEncoder): def default(self, o): return round(o, 10) if isinstance(o, float) else super().default(o)
Dead Ends
Common approaches that don't work:
-
Use float for monetary/financial values and round at display time
90% fail
Rounding at display doesn't fix intermediate calculations. $0.1 + $0.2 stored as float = $0.30000000000000004 in the database.
-
Round float to 2 decimal places before JSON serialization
82% fail
round(0.1 + 0.2, 2) == 0.3 in Python, but round(2.675, 2) == 2.67 (not 2.68) due to float representation of 2.675.