article

JavaScript Math is a Lie

2 min read

Ever tried 0.1 + 0.2 === 0.3 in JS? Yeah, it returns false. In this satirical-yet-informative piece, we dig into why JavaScript math feels like it’s gaslighting us and how to work around it without losing your mind.

The Crime Scene

Open a console. Type this. Weep.

0.1 + 0.2 === 0.3 // false
0.1 + 0.2          // 0.30000000000000004

You are not hallucinating. JavaScript is not uniquely broken. Welcome to IEEE 754 double-precision floating point — the standard used by virtually every modern programming language.

Why It Happens

Computers store numbers in binary. Most decimal fractions cannot be represented exactly in binary, just like 1/3 cannot be written exactly in decimal. 0.1 in binary is a repeating fraction — it gets rounded to the nearest representable value when stored.

When you add two of these rounded approximations together, the rounding errors compound, and you get 0.30000000000000004 instead of 0.3.

This is not a bug. It is working as specified.

Other Classics

9007199254740992 + 1 === 9007199254740992 // true — integer overflow
0.1 + 0.7                                 // 0.7999999999999999
Number.MAX_SAFE_INTEGER                   // 9007199254740991

Number.MAX_SAFE_INTEGER is the largest integer that can be represented exactly. Beyond it, integers start losing precision too.

How to Cope

For display — round before showing:

(0.1 + 0.2).toFixed(2) // "0.30"

For comparison — use an epsilon:

const EPSILON = Number.EPSILON;
Math.abs(0.1 + 0.2 - 0.3) < EPSILON; // true

For currency and high-precision arithmetic — use integers:

Store amounts in the smallest unit (cents, not dollars) and do all arithmetic in integers. Convert only at the display layer.

// Store $12.50 as 1250 cents
const total = 1250 + 499; // $12.50 + $4.99 = $17.49
console.log((total / 100).toFixed(2)); // "17.49"

For very large integers — use BigInt:

const big = 9007199254740993n; // exact

The Takeaway

JavaScript’s number type is not a calculator — it is a floating-point approximation machine. Most of the time this does not matter. When it does matter (money, cryptography, precise comparisons), know the tools: toFixed, epsilon comparison, integer arithmetic, or BigInt. And never trust === with decimals.