Belajar
← All lessons

How floating point works

Why 0.1 + 0.2 isn't 0.3

compare.js

const a = 0.1 + 0.2;// the shortest decimal that rounds back to the same doubleconsole.log(a); // 0.30000000000000004 // two different doubles, so strict equality failsa === 0.3; // false // compare with a tolerance insteadMath.abs(a - 0.3) < Number.EPSILON; // or keep money in integer centsconst total = 10 + 20; // 30 cents

bits.js

// read the raw 64 bits behind a numberconst view = new DataView(new ArrayBuffer(8));view.setFloat64(0, x);const raw = view.getBigUint64(0); const sign = raw >> 63n;const exponent = Number((raw >> 52n) & 0x7ffn);const mantissa = raw & 0xfffffffffffffn; // normal numbers: a hidden 1, then the 52 mantissa bitsconst value = (-1) ** Number(sign)  * (1 + Number(mantissa) / 2 ** 52)  * 2 ** (exponent - 1023);

Look inside a double type any number

Number
Or try
64 bits

Fields
sign
exponent
mantissa
value
stored
prints as

bits.js

// read the raw 64 bits behind a numberconst view = new DataView(new ArrayBuffer(8));view.setFloat64(0, x);const raw = view.getBigUint64(0); const sign = raw >> 63n;const exponent = Number((raw >> 52n) & 0x7ffn);const mantissa = raw & 0xfffffffffffffn; // normal numbers: a hidden 1, then the 52 mantissa bitsconst value = (-1) ** Number(sign)  * (1 + Number(mantissa) / 2 ** 52)  * 2 ** (exponent - 1023);

The gaps grow with the number slide up past 2^53

Numbers near20
Integers x to x + 8. Ticks on top are doubles, the ones below are integers
x
next double
gap
x + 1

Number.MAX_SAFE_INTEGER is 2^53 − 1. Past it, IDs and money amounts can silently change

gaps.js

// the distance to the next double grows with the numberNumber.EPSILON;            // 2 ** -52, the gap after 12 ** 52 + 0.5;             // 4503599627370496 // past 2^53, not every integer is a doubleNumber.MAX_SAFE_INTEGER;   // 2 ** 53 - 12 ** 53 + 1 === 2 ** 53;   // true

Topics

Next: How UTF-8 works

Open lesson