Course contentsShow
← JavaScript
Lesson 243 of 2,7237. Arithmetic and OperatorsFree lesson

Floating-Point Precision in Arithmetic

Identify precision issues in operations like 0.1 + 0.2 and strategies to mitigate rounding errors.

Floating-Point Precision in Arithmetic

What you'll learn: Why 0.1 + 0.2 doesn't equal 0.3 in JavaScript and how to work around it.

The Surprise

Try this in your console: 0.1 + 0.2. You might expect 0.3, but JavaScript gives you 0.30000000000000004. Wait, what?

This isn't a bug—it's how computers store decimal numbers. JavaScript uses binary floating-point arithmetic (following the IEEE 754 standard), which can't perfectly represent some decimal fractions, just like you can't write 1/3 exactly in decimal (0.333...).

Why It Happens

Think of it like trying to describe the color blue using only red and green paint. Some values just can't be represented exactly with the tools available. In binary (base-2), numbers like 0.1 and 0.2 become repeating decimals, so the computer stores approximations. When you add these approximations, tiny errors compound.

console.log(0.1 + 0.2);              // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3);      // false

Strategies to Handle This

Round to a fixed precision when displaying or comparing:

console.log((0.1 + 0.2).toFixed(2)); // "0.30" (string)
console.log(+(0.1 + 0.2).toFixed(10)); // 0.3 (number)

Compare with a small tolerance instead of exact equality:

let result = 0.1 + 0.2;
let expected = 0.3;
console.log(result - expected < 0.0001); // true - "close enough"

Work with integers when possible (e.g., use cents instead of dollars).

Key Takeaway: Floating-point arithmetic in JavaScript isn't perfectly precise due to binary representation limits. Always round for display and use tolerance ranges for comparisons instead of exact equality checks.