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

Also available as: JSON · Markdown
85%Fix Rate
90%Confidence
3Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
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.

generic

Workarounds

  1. 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"
  2. 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.
  3. 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:

  1. 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.

  2. 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.