0
0
JavascriptDebug / FixBeginner · 3 min read

How to Fix Floating Point Precision in JavaScript

Floating point precision errors in JavaScript happen because numbers are stored in binary format that can't exactly represent some decimals. To fix this, use 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.

javascript
console.log(0.1 + 0.2);
console.log(0.1 + 0.2 === 0.3);
Output
0.30000000000000004 false
🔧

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.

javascript
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
Output
0.3 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.

javascript
const a = 0.1 + 0.2;
const b = 0.3;
const epsilon = 0.00001;
console.log(Math.abs(a - b) < epsilon); // true
Output
true

Key Takeaways

Floating point errors happen because decimals can't be exactly stored in binary.
Use rounding methods like toFixed() or Math.round() to fix precision issues.
Avoid direct equality checks on floats; compare with a small tolerance instead.
Use decimal libraries for precise and complex decimal math.
Always round results when working with money or measurements.