🔢 Binary Representation Basics
How many numbers can you represent?
1 bit → 2¹ = 2 numbers
2 bits → 2² = 4 numbers
N bits → 2ᴺ numbers
Try it yourself:
Click a button to see the possible values!
⚠️ JavaScript Number Limits
Note: JavaScript uses an object-oriented approach for number properties and methods.
Basic Limits
console.log(Number.MAX_VALUE);
// 1.7976931348623157e+308
console.log(Number.MIN_VALUE);
// 5e-324 (smallest positive number, not most negative!)
😱 It Gets Worse...
Safe Integer Limits
console.log(Number.MAX_SAFE_INTEGER);
// 9007199254740991
console.log(Number.MIN_SAFE_INTEGER);
// -9007199254740991
What happens between Number.MAX_SAFE_INTEGER and Number.MAX_VALUE?
JavaScript loses precision! Integers beyond the safe range may not be represented accurately.
JavaScript loses precision! Integers beyond the safe range may not be represented accurately.
🤯 More Down-to-Earth Examples
The Famous 0.1 + 0.2 Problem
console.log(0.1 + 0.2); // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // false
console.log(0.3); // 0.3 (but 0.3 is not really 0.3!)
JavaScript's printing tries to be "nice" - it rounds display values to hide floating-point errors.
Forcing "Not-Nice" Printed Values
console.log((0.1 + 0.2).toPrecision(20));
// "0.30000000000000004441"
console.log((0.3).toPrecision(20));
// "0.29999999999999998890"
🔧 BigInt to the Rescue (Sort of)
- Computationally more expensive than regular numbers
- Works for "any" integers - no upper limit
- Does NOT work for decimal numbers
- No good way to do decimals exactly in JavaScript
- Alternative: You could implement rational numbers (fractions)
BigInt Notation
const bigNumber = 123456789012345678901234567890n;
// Notice the "n" at the end!
const anotherBig = BigInt("987654321098765432109876543210");