How to Fix JavaScript Floating Point Precision Issues
In this tutorial, you'll learn about How to Fix JavaScript Floating Point Precision Issues. We cover key concepts, practical examples, and best practices.
The Problem
JavaScript floating point arithmetic produces unexpected results like 0.1 + 0.2 === 0.3 returning false due to IEEE 754 binary representation, where decimals like 0.1 cannot be represented exactly in binary.
Quick Fix
Step 1: Round to a fixed number of decimals
Use toFixed() or Math.round() for display:
const result = 0.1 + 0.2;
console.log(result);
0.30000000000000004
Round for comparison:
const result = 0.1 + 0.2;
const rounded = Math.round(result * 100) / 100;
console.log(rounded);
console.log(rounded === 0.3);
0.3
true
Step 2: Use Number.EPSILON for comparisons
Compare with a tolerance threshold:
function nearlyEqual(a, b) {
return Math.abs(a - b) < Number.EPSILON;
}
console.log(nearlyEqual(0.1 + 0.2, 0.3));
true
Step 3: Convert to integers for monetary calculations
Multiply before calculating and divide after:
const price = 9.99;
const quantity = 3;
const total = price * quantity;
console.log(total);
29.969999999999999
Use integer cents:
const priceCents = 999;
const quantity = 3;
const totalCents = priceCents * quantity;
const total = (totalCents / 100).toFixed(2);
console.log(total);
29.97
Step 4: Use a decimal library
For exact decimal arithmetic, use a library:
// Using decimal.js
const Decimal = require('decimal.js');
const a = new Decimal('0.1');
const b = new Decimal('0.2');
const sum = a.plus(b).toNumber();
console.log(sum);
console.log(sum === 0.3);
0.3
true
Prevention
- Never compare floating point numbers with
===without rounding. - Use
toFixed(2)for currency display. - Work in integer units (cents, pennies) for financial calculations.
- Use
Number.EPSILONfor tolerance-based comparisons. - Use libraries like
decimal.jsorcurrency.jsfor exact arithmetic.
Common Mistakes with floating point
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
These mistakes appear frequently in real-world JS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro