How to Fix Floating Point Precision in JavaScript
toFixed(), Math.round() with scaling, or libraries like decimal.js to handle precise decimal math.Why This Happens
JavaScript uses a binary format called IEEE 754 to store numbers. Some decimal numbers can't be exactly represented in this format, causing small rounding errors. This is why 0.1 + 0.2 does not exactly equal 0.3.
console.log(0.1 + 0.2); console.log(0.1 + 0.2 === 0.3);
The Fix
To fix floating point precision, round the result to a fixed number of decimal places using toFixed() or multiply and divide with Math.round(). This removes tiny errors and gives the expected result.
const sum = 0.1 + 0.2; const fixedSum = Number(sum.toFixed(2)); console.log(fixedSum); // 0.3 // Or using Math.round const roundedSum = Math.round((0.1 + 0.2) * 100) / 100; console.log(roundedSum); // 0.3
Prevention
To avoid floating point errors, always round results when working with decimals, especially for money or measurements. Use libraries like decimal.js for complex calculations. Also, avoid comparing floats directly; instead, check if the difference is smaller than a tiny threshold.
Related Errors
Similar issues include comparing floating numbers directly, which can fail due to tiny differences. Use an epsilon value to check if numbers are close enough instead of exactly equal.
const a = 0.1 + 0.2; const b = 0.3; const epsilon = 0.00001; console.log(Math.abs(a - b) < epsilon); // true