Never Use Floats for Money
Every codebase I have inherited has had this bug somewhere. Usually in a totals column, occasionally in a payments table, once in a payroll system that had been quietly losing about forty dollars a month for three years. 0.1+0.2 // 0.30000000000000004 0.1+0.2===0.3 // false That is not a JavaScript quirk. It is IEEE 754, and it behaves the same way in Python, Java, C, Go, Rust and everything else…
Many codebases contain bugs where amounts are stored as floating-point numbers, often in totals or payments tables. A classic example is adding 0.1 and 0.2, which results in an unexpected value of 0.30000000000000004 instead of the expected 0.3. This issue arises because binary floating-point cannot represent many decimal fractions precisely. The best explanation of this phenomenon is found at The Floating Point Guide.
The consequences are that every arithmetic operation on a decimal value introduces a small error, which accumulates over time and does not cancel out. For instance, a loop that adds 0.1 ten times to a variable may not reach exactly 1.0 due to these errors. Moreover, floating-point addition is not associative, meaning the order of operations affects the result.
This can lead to inconsistent totals depending on evaluation order, rendering reconciliations unreliable and causing intermittent failures in systems like regulated gaming platforms.
To prevent these issues, money should be stored as integers representing the smallest unit (e.g., cents instead of dollars). This eliminates floating-point errors, as integer arithmetic is exact. When necessary, libraries like decimal.js or big.js provide exact decimal arithmetic for handling fractional values. It is crucial to avoid using floating-point types for monetary values and instead opt for integer or decimal types that ensure precise calculations.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.