JavaScript Number Methods Reference
Browse all Number static properties, static methods, instance methods, and 17 Math methods — with signatures, edge cases, and a live code runner
8 / 8 properties
0.1 + 0.2 === 0.3 is false. parseInt("08") returns 8 in modern engines but returned 0 in old ones. Number.isNaN("hello") returns false while isNaN("hello") returns true. Math.round(-0.5) returns 0, not -1. JavaScript numbers have enough gotchas that you need a reference that shows the edge cases alongside the normal usage — not just the method signatures.
Why This Reference (Not MDN)
MDN documents Number, Math, parseInt, and isNaN across dozens of pages. This reference puts everything on one page — static properties (MAX_SAFE_INTEGER, EPSILON, NaN), static methods (isFinite, isInteger, isNaN, parseFloat, parseInt), instance methods (toFixed, toPrecision, toExponential), and key Math methods — with edge cases highlighted.
JavaScript Numbers — The Fundamentals
JavaScript uses the IEEE 754 double-precision (64-bit) floating-point standard for all numbers. There is a single number type — no separate int or float — which means integers and decimals share the same representation with the same limitations.
console.log(typeof 42); // "number"
console.log(typeof 3.14); // "number"
console.log(typeof NaN); // "number" (!)
console.log(typeof Infinity); // "number"
The IEEE 754 Double-Precision Model
A 64-bit double has:
- 1 sign bit
- 11 exponent bits
- 52 mantissa (significand) bits
This gives roughly 15–17 significant decimal digits and a range from ±5e-324 to ±1.8e308. Integers are represented exactly only when they fit within the 52-bit mantissa (up to 2⁵³ − 1 = 9,007,199,254,740,991).
The Floating-Point Pitfall
console.log(0.1 + 0.2); // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // false
Neither 0.1 nor 0.2 has an exact binary representation, so their sum accumulates a tiny error. The standard fix is epsilon comparison:
function approxEqual(a, b) {
return Math.abs(a - b) < Number.EPSILON;
}
console.log(approxEqual(0.1 + 0.2, 0.3)); // true
For financial calculations, use integer arithmetic in cents (multiply by 100) or a library like decimal.js.
Number Static Properties
The Number constructor exposes eight built-in constants that describe the limits and special values of the double-precision float:
| Property | Value | Since |
|---|---|---|
Number.MAX_SAFE_INTEGER | 9007199254740991 | ES2015 |
Number.MIN_SAFE_INTEGER | −9007199254740991 | ES2015 |
Number.MAX_VALUE | ≈1.8×10³⁰⁸ | ES1 |
Number.MIN_VALUE | 5×10⁻³²⁴ | ES1 |
Number.EPSILON | ≈2.22×10⁻¹⁶ | ES2015 |
Number.NaN | NaN | ES1 |
Number.POSITIVE_INFINITY | Infinity | ES1 |
Number.NEGATIVE_INFINITY | −Infinity | ES1 |
Safe Integer Range
A “safe integer” is an integer that can be uniquely and exactly represented as a double. Once you go beyond ±2⁵³−1, multiple integers map to the same float:
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
console.log(Number.MAX_SAFE_INTEGER + 1); // 9007199254740992
console.log(Number.MAX_SAFE_INTEGER + 2); // 9007199254740992 (same!)
console.log(9007199254740992 === 9007199254740993); // true (!)
Use BigInt for integers beyond this range:
const big = 9007199254740991n + 2n;
console.log(big); // 9007199254740993n (correct)
Number Static Methods
All four Number.isXxx() methods are strict — they return false for non-number types without any coercion. This makes them safer than their global counterparts.
isFinite vs. isNaN — Global vs. Number
// Global versions coerce their argument to a number first:
isFinite("42"); // true (coerces "42" → 42 → finite)
isNaN("hello"); // true (coerces "hello" → NaN)
// Number versions do NOT coerce:
Number.isFinite("42"); // false (string is not a finite number)
Number.isNaN("hello"); // false (string is not NaN)
Always prefer the Number.* versions to avoid coercion surprises.
Number.parseFloat vs. Number.parseInt
Both are identical to the global parseFloat() and parseInt(). They were added to Number in ES2015 to consolidate the API:
Number.parseInt("42.9px"); // 42
Number.parseFloat("42.9px"); // 42.9
// Always provide the radix for parseInt:
Number.parseInt("0xFF", 16); // 255
Number.parseInt("11", 2); // 3
Number Instance Methods
These methods are available on every number primitive (and Number object). They all return strings — not numbers — except valueOf().
toFixed — Currency and Financial Display
const price = 9.5;
console.log(price.toFixed(2)); // "9.50" (padded)
// Common gotcha with floats:
console.log((1.005).toFixed(2)); // "1.00" (float precision!)
// 1.005 is stored as 1.00499999... in float64
toPrecision — Significant Digits
const pi = Math.PI;
console.log(pi.toPrecision(4)); // "3.142"
console.log(pi.toPrecision(10)); // "3.141592654"
toString — Base Conversion
// Convert decimal to other bases:
console.log((255).toString(16)); // "ff"
console.log((255).toString(2)); // "11111111"
console.log((255).toString(8)); // "377"
// Parse back with parseInt:
console.log(parseInt("ff", 16)); // 255
toLocaleString — Human-Readable Numbers
const million = 1000000;
// Locale-sensitive thousands separators:
console.log(million.toLocaleString("en-US")); // "1,000,000"
console.log(million.toLocaleString("de-DE")); // "1.000.000"
// Currency:
console.log(million.toLocaleString("en-US", {
style: "currency", currency: "USD"
})); // "$1,000,000.00"
// Compact notation:
console.log(million.toLocaleString("en", { notation: "compact" })); // "1M"
Math Methods
Math is a plain object (not a constructor) that groups mathematical constants and functions. All methods accept and return number values.
Math Constants
Math.PI; // 3.141592653589793
Math.E; // 2.718281828459045
Math.SQRT2; // 1.4142135623730951
Math.LN2; // 0.6931471805599453
Math.LN10; // 2.302585092994046
Math.LOG2E; // 1.4426950408889634
Math.LOG10E; // 0.4342944819032518
Rounding Methods Compared
// ceil floor round trunc
// 4.1: 5 4 4 4
// 4.5: 5 4 5 4
// 4.9: 5 4 5 4
// -4.1: -4 -5 -4 -4
// -4.5: -4 -5 -4 -4
// -4.9: -4 -5 -5 -4
Key differences:
ceil: always rounds toward +∞ (up for positive, less-negative for negative)floor: always rounds toward −∞ (down for positive, more-negative for negative)round: rounds to nearest; ties go toward +∞trunc: removes the fractional part, toward zero
Generating Random Numbers
// Float in [0, 1):
Math.random();
// Integer in [0, n):
Math.floor(Math.random() * n);
// Integer in [min, max] inclusive:
Math.floor(Math.random() * (max - min + 1)) + min;
// Shuffle an array (Fisher-Yates):
function shuffle(arr) {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
For cryptographic randomness, use:
const buf = new Uint32Array(1);
crypto.getRandomValues(buf);
console.log(buf[0]); // cryptographically secure random uint32
Logarithms and Exponentiation
// Natural log (base e):
Math.log(Math.E); // 1
Math.log(1); // 0
Math.log(0); // -Infinity
// Base-2 log (bit counting):
Math.log2(8); // 3
Math.floor(Math.log2(n)) + 1; // number of bits to represent n
// Base-10 log (number of digits):
Math.floor(Math.log10(999)) + 1; // 3 (three digits)
Math.floor(Math.log10(1000)) + 1; // 4
// Exponentiation:
Math.pow(2, 32); // 4294967296
2 ** 32; // 4294967296 (ES2016+, prefer ** over Math.pow)
Euclidean Distance with Math.hypot
// Naive approach: may overflow for very large numbers
const dist1 = Math.sqrt(dx * dx + dy * dy);
// Math.hypot: avoids intermediate overflow
const dist2 = Math.hypot(dx, dy);
// 3D distance:
const dist3d = Math.hypot(dx, dy, dz);
Common Patterns
Check for Valid Number (Not NaN, Not Infinity)
function isValidNumber(x) {
return typeof x === "number" && Number.isFinite(x);
}
Safe Division
function safeDivide(a, b) {
if (b === 0) return null;
return a / b;
}
Clamp a Value
function clamp(value, min, max) {
return Math.max(min, Math.min(max, value));
}
console.log(clamp(150, 0, 100)); // 100
console.log(clamp(-5, 0, 100)); // 0
Round to N Decimal Places
function roundTo(n, decimals) {
const factor = 10 ** decimals;
return Math.round(n * factor) / factor;
}
console.log(roundTo(1.2345, 2)); // 1.23
Format Bytes
function formatBytes(bytes, decimals = 2) {
if (bytes === 0) return "0 B";
const k = 1024;
const units = ["B", "KB", "MB", "GB", "TB"];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${(bytes / k ** i).toFixed(decimals)} ${units[i]}`;
}
console.log(formatBytes(1536)); // "1.50 KB"
Parse Currency String to Number
function parseCurrency(str) {
// Remove currency symbol, spaces, commas:
return Number.parseFloat(str.replace(/[^0-9.-]/g, ""));
}
console.log(parseCurrency("$1,234.56")); // 1234.56
Frequently Asked Questions
What is the difference between Number.isNaN() and global isNaN()?
Number.isNaN() returns true only if the value is exactly NaN. It never coerces its argument. Global isNaN() coerces the argument to a number first, so isNaN('hello') returns true because Number('hello') is NaN. Use Number.isNaN() to avoid accidental coercion.
Why does (0.1 + 0.2) !== 0.3?
JavaScript uses 64-bit IEEE 754 floating-point arithmetic. Neither 0.1 nor 0.2 has an exact binary representation, so adding them produces 0.30000000000000004. Compare floats using Math.abs(a - b) < Number.EPSILON for near-equality, or convert to integers (multiply by 100) for exact arithmetic.
What is the difference between toFixed() and toPrecision()?
toFixed(n) specifies the number of decimal places after the point. toPrecision(n) specifies the total number of significant digits. For 123.456: toFixed(2) → "123.46", toPrecision(5) → "123.46". For small numbers: (0.001234).toFixed(5) → "0.00123", (0.001234).toPrecision(5) → "0.0012340".
When should I use BigInt instead of Number?
Use BigInt when you need to work with integers larger than Number.MAX_SAFE_INTEGER (9,007,199,254,740,991) or when exact integer arithmetic is critical. BigInt cannot be mixed with regular Number arithmetic — you must convert explicitly. BigInt is not suitable for floating-point calculations.
Is Math.random() safe for cryptography?
No. Math.random() is a pseudo-random number generator (PRNG) that is seeded deterministically and is not cryptographically secure. For security-sensitive use cases (token generation, passwords, salts), use crypto.getRandomValues() in browsers or crypto.randomBytes() in Node.js.
What is Number.EPSILON and how do I use it?
Number.EPSILON is the smallest difference between two representable 64-bit floats near 1.0 (approximately 2.22×10⁻¹⁶). Use it to check near-equality for floats close to 1: Math.abs(a - b) < Number.EPSILON. For numbers far from 1, scale the tolerance: Math.abs(a - b) < Number.EPSILON * Math.max(Math.abs(a), Math.abs(b)).