JSONmedium3-5 years

A payment API returns `{"amountPaid": 19.99, "amountDue": 19.99}`. Both values print as `19.99` after being parsed into Java `double`s, but `amountPaid.equals(amountDue)` sometimes returns `false`. How can two values that print identically compare as unequal, and what's the actual fix?

19.99 has no exact representation in binary floating point — what actually gets stored is the nearest representable double, and printing rounds that back to 19.99 for display, which hides the tiny error underneath. Two separate computations that each round to 19.99 when printed can still hold two genuinely different nearest-representable values internally — especially if one of them passed through an extra step like a currency conversion — and equals() on a double compares the raw stored bits, not the printed text, so it sees exactly the difference the print statement was hiding. The actual fix is upstream of the comparison: never store money as double. Parse it as BigDecimal (exact decimal digits, no binary rounding) or as an integer count of the smallest currency unit (1999 paise, not 19.99 rupees) — the same rule for the Java type that JSON's own lack of declared number precision already requires at the wire level.

The lesson behind it →
More on JSON