Floating Point Accumulation Drift
Quick summary
Adding 0.1 many times does not give a clean multiple — tiny errors accumulate and the final sum drifts from the true value.
Why this happens
Looping and adding floats instead of multiplying once
Comparing the accumulated sum with an exact expected value using ===
Using floats for money where cents should be integers
Minimal example
let total = 0;
for (let i = 0; i < 10; i++) total += 0.1;
console.log(total === 1); // false — total is 0.9999999999999999let total = 0;
for (let i = 0; i < 10; i++) total += 0.1;
console.log(Math.round(total * 10) / 10 === 1); // trueAdding 0.1 ten times yields 0.9999999999999999 due to binary rounding, so the === 1 check fails. Rounding to one decimal place restores the expected value.
How to diagnose
Print the accumulated sum with full precision to see the drift
Compare with the mathematically expected value to measure the error
Check whether the loop could be replaced by a single multiplication
How to fix
Replace repeated addition with a single multiplication when possible
Round the accumulated result to the needed precision before use
Use integer cents or a decimal library for financial calculations
How to prevent
Avoid accumulating floats — prefer multiplication or integer math
Use a decimal library for money and other exact-value domains
Related Resources
Related Glossary
Related Lessons
- Numbers and Math
Learn about floating-point limits.