Numbers & Math Object
JavaScript uses a single 64-bit floating-point type for
all numbers. Learn integers, decimals, special values like
NaN and Infinity,
precision pitfalls, handy number methods, and the full power of the built-in
Math object.
The Number Type
Unlike many languages that have separate types for integers and decimals,
JavaScript has a single Number type that covers both. Under the hood every
number is stored as a 64-bit double-precision float following the
IEEE 754 standard — the same format used by C's double.
e for very large or very small numbers.
n.
// Integer and float
const age = 25;`
const price = 9.99;
const negative = -42;
// Alternative bases
const binary = 0b1010; // → 10
const octal = 0o17; // → 15
const hex = 0xFF; // → 255
// Exponential
const big = 1.5e6; // → 1 500 000
const small = 2.9e-4; // → 0.00029
// Numeric separators (ES2021)
const million = 1_000_000; // same as 1000000
// BigInt (ES2020)
const big2 = 9999999999999999n;
typeof age; // → "number"
typeof big2; // → "bigint"Special Numeric Values
The Number type includes a handful of special values that represent edge cases. Understanding them prevents subtle bugs:
NaN !== NaN is always true.
-Infinity directly.
// NaN — Not a Number
console.log(0 / 0); // NaN
console.log("hello" * 2); // NaN
console.log(Math.sqrt(-1)); // NaN
// NaN is the only value not equal to itself!
console.log(NaN === NaN); // false ← always!
// ✅ Correct way to check for NaN
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN("text")); // false ← better than global isNaN()
console.log(isNaN("text")); // true ← global isNaN coerces first
// Infinity
console.log(1 / 0); // Infinity
console.log(-1 / 0); // -Infinity
console.log(Infinity + 1); // Infinity
console.log(isFinite(99)); // true
console.log(isFinite(Infinity)); // false
// Negative zero
console.log(-0 === 0); // true (quirk!)
console.log(Object.is(-0, 0)); // false (precise check)
Number.isNaN() instead of the global isNaN(). The global
version coerces its argument to a number first, so isNaN("hello") returns
true even though "hello" is a string, not NaN.
Floating-Point Precision
Because numbers are stored in binary floating-point, some decimal values can't be represented exactly. This is not a JavaScript bug — it's how IEEE 754 works in every language that uses it (Python, Java, C…).
// The classic gotcha
console.log(0.1 + 0.2); // 0.30000000000000004
// ✅ Option 1 — epsilon comparison (best for checks)
function almostEqual(a, b) {
return Math.abs(a - b) < Number.EPSILON;
}
console.log(almostEqual(0.1 + 0.2, 0.3)); // true
// ✅ Option 2 — toFixed (best for display)
const result = (0.1 + 0.2).toFixed(2);
console.log(result); // "0.30" (string)
console.log(+result); // 0.3 (back to number)
// ✅ Option 3 — multiply to integer, then divide
const safe = (0.1 * 10 + 0.2 * 10) / 10;
console.log(safe); // 0.3 ✓
// Safe integer range
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991 (2⁵³ − 1)
console.log(Number.MIN_SAFE_INTEGER); // -9007199254740991
console.log(Number.isSafeInteger(42)); // true
decimal.js or big.js. Never rely on floating-point equality for
money.
Number Methods & Conversion
JavaScript provides both instance methods (called on a
number value) and static methods on the Number
constructor for parsing and validation.
| Method / Property | Description | Example → Result |
|---|---|---|
| .toFixed(n) | Format to n decimal places, returns a string | (3.14159).toFixed(2) → "3.14" |
| .toPrecision(n) | Format to n significant digits, returns a string | (123.456).toPrecision(5) → "123.46" |
| .toString(base) | Convert to a string in a given base (2–36) | (255).toString(16) → "ff" |
| Number(value) | Convert any value to a number | Number("42") → 42 · Number(true) → 1 |
| parseInt(str, base) | Parse a string and return an integer. Always supply the base (10). | parseInt("42px", 10) → 42 |
| parseFloat(str) | Parse a string and return a floating-point number | parseFloat("3.14rem") → 3.14 |
| Number.isNaN(val) | Returns true only if the value is literally NaN |
Number.isNaN(NaN) → true |
| Number.isFinite(val) | Returns true if value is a finite number |
Number.isFinite(Infinity) → false |
| Number.isInteger(val) | Returns true if value is an integer |
Number.isInteger(4.0) → true |
| Number.EPSILON | Smallest difference between two representable floats ≈ 2.22e-16 | Used for float equality checks |
const n = 3.14159265;
// Instance methods — called on a number value
n.toFixed(2); // "3.14"
n.toPrecision(4); // "3.142"
n.toString(); // "3.14159265"
(255).toString(16); // "ff" — hex
(10).toString(2); // "1010" — binary
// Conversion functions
Number("42"); // 42
Number(""); // 0
Number(true); // 1
Number(false); // 0
Number(null); // 0
Number("abc"); // NaN
// parseInt & parseFloat
parseInt("42px", 10); // 42 — stops at non-digit
parseInt("0xff", 16); // 255
parseFloat("3.5em"); // 3.5
parseInt("abc", 10); // NaN
// Static checks
Number.isNaN(NaN); // true
Number.isFinite(99); // true
Number.isInteger(4); // true
Number.isInteger(4.5);// false
The Math Object
Math is a built-in object (not a
constructor) that exposes mathematical constants and functions as static properties. You never
create an instance — you call methods directly like
Math.round().
Math methods work only with the regular Number type — they
do not work with BigInt. Passing a BigInt to
Math.abs() will throw a TypeError.
Math Constants
The Math object exposes several
important mathematical constants as read-only properties:
Math Methods
These are the most commonly used methods on the
Math object, grouped by category:
base ** exp.
NaN for negative
input.1, -1, or 0
depending on the sign of the number.// ── Rounding variants ────────────────────────────────────────
Math.round(4.5); // 5
Math.floor(4.9); // 4 ← always down
Math.ceil(4.1); // 5 ← always up
Math.trunc(-4.9); // -4 ← towards zero, not floor
Math.floor(-4.1); // -5 ← note difference!
// ── Random integer between min and max (inclusive) ──────────
function randInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randInt(1, 6)); // dice roll: 1–6
// ── Power and roots ──────────────────────────────────────────
Math.pow(2, 10); // 1024
2 ** 10; // 1024 — ES7 exponentiation operator
Math.sqrt(625); // 25
Math.cbrt(125); // 5
// ── Min / Max of an array using spread ───────────────────────
const nums = [3, 1, 9, 4, 7];
Math.max(...nums); // 9
Math.min(...nums); // 1
// ── Circle area ──────────────────────────────────────────────
const radius = 7;
const area = Math.PI * Math.pow(radius, 2);
console.log(area.toFixed(2)); // "153.94"
// ── Clamp a value between min and max ────────────────────────
const clamp = (val, min, max) => Math.min(Math.max(val, min), max);
console.log(clamp(150, 0, 100)); // 100
console.log(clamp(-10, 0, 100)); // 0
Try It — Live Editor
Experiment with numbers and Math methods. Try changing the radius, generating random numbers, or testing the precision examples from above.
Common Patterns & Recipes
These are everyday number utilities you'll find yourself writing repeatedly in real projects:
// ── Random integer in range [min, max] ──────────────────────
const randInt = (min, max) =>
Math.floor(Math.random() * (max - min + 1)) + min;
// ── Clamp value between bounds ───────────────────────────────
const clamp = (val, min, max) =>
Math.min(Math.max(val, min), max);
// ── Round to N decimal places ────────────────────────────────
const roundTo = (num, places) =>
Math.round(num * 10 ** places) / 10 ** places;
roundTo(3.14159, 3); // 3.142
// ── Check if a number is even / odd ─────────────────────────
const isEven = n => n % 2 === 0;
const isOdd = n => n % 2 !== 0;
// ── Format currency (Indian style) ──────────────────────────
const formatINR = (amount) =>
amount.toLocaleString("en-IN", { style: "currency", currency: "INR" });
formatINR(1234567.89); // "₹12,34,567.89"
// ── Degrees ↔ Radians ────────────────────────────────────────
const toRad = deg => deg * (Math.PI / 180);
const toDeg = rad => rad * (180 / Math.PI);
// ── Fibonacci with memoisation ───────────────────────────────
const cache = {};
function fib(n) {
if (n <= 1) return n;
return cache[n] ??= fib(n - 1) + fib(n - 2);
}
console.log(fib(10)); // 55typeof NaN return in JavaScript?- JavaScript uses a single 64-bit IEEE 754 float type for all numbers — integers and decimals alike.
- Numeric literals support integer, float, binary (
0b), octal (0o), hex (0xFF), and exponential (1e6) forms. - Special values include NaN (invalid operation), Infinity / −Infinity (overflow), and −0 (signed zero).
- Always use
Number.isNaN()— not the globalisNaN()— to check for NaN safely. - Float comparison with
===is unreliable — useNumber.EPSILONtolerance or.toFixed()for display. - Key number methods:
toFixed(),parseInt(),parseFloat(), andNumber.isInteger(). Mathis a static object — never instantiated. It provides constants (Math.PI) and methods (round,floor,ceil,random,pow,sqrt…).- Generate a random integer in a range with
Math.floor(Math.random() * (max - min + 1)) + min.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.