4 min read
•Question 46 of 50mediumHow do Numbers work in JavaScript?
Understanding number types and precision.
What You'll Learn
- Number representation
- Floating point issues
- BigInt for large numbers
Number Basics
JavaScript uses 64-bit floating point (IEEE 754) for all numbers.
code.jsJavaScript
// Same type
typeof 42; // 'number'
typeof 42.5; // 'number'
// Special values
Infinity
-Infinity
NaN // Not a Number
// Checking
isNaN(NaN); // true
isFinite(Infinity); // false
Number.isInteger(42); // trueFloating Point Issues
code.jsJavaScript
// Famous precision problem
0.1 + 0.2; // 0.30000000000000004
0.1 + 0.2 === 0.3; // false
// Solution: Compare with epsilon
Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON; // true
// Or use integers
const priceInCents = 999;
const dollars = priceInCents / 100; // 9.99Safe Integer Range
code.jsJavaScript
Number.MAX_SAFE_INTEGER; // 9007199254740991
Number.MIN_SAFE_INTEGER; // -9007199254740991
Number.isSafeInteger(9007199254740991); // true
Number.isSafeInteger(9007199254740992); // falseBigInt
For integers larger than MAX_SAFE_INTEGER.
code.jsJavaScript
const big = 9007199254740992n;
const also = BigInt('9007199254740992');
// Operations
big + 1n; // 9007199254740993n
big * 2n; // 18014398509481984n
// Cannot mix with regular numbers
big + 1; // TypeError
big + BigInt(1); // OKNumber Methods
code.jsJavaScript
const num = 3.14159;
num.toFixed(2); // '3.14'
num.toPrecision(4); // '3.142'
num.toString(2); // '11.001001...' (binary)
parseInt('42px'); // 42
parseFloat('3.14'); // 3.14