Tutorials JavaScript Numbers & Math Object
Ch 9 / 78
Chapter 10 Beginner 8 min read JavaScript

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.

What you'll learn
How JavaScript stores all numbers as IEEE-754 floats
Special values — NaN, Infinity, −Infinity, −0
Floating-point precision gotchas and how to handle them
Number methods — toFixed, parseInt, parseFloat, isNaN
Math constants — PI, E, LN2, SQRT2 and more
Math methods — round, floor, ceil, abs, pow, random

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.

Integer
Whole numbers, positive or negative. Stored exactly up to ±2⁵³−1.
42 · -7 · 0 · 1_000_000
Float
Numbers with a decimal point. Subject to floating-point precision issues.
3.14 · -0.5 · 1.2e10
Binary / Octal / Hex
Numeric literals in other bases. All stored the same way internally.
0b1010 · 0o17 · 0xFF
Exponential Notation
Scientific notation with e for very large or very small numbers.
1.5e6 · 2.9e-4
Numeric Separators
ES2021 — use underscores to make large literals more readable. Ignored by the engine.
1_000_000 · 0xFF_AB_CD
BigInt
ES2020 — a separate type for integers beyond the safe integer limit. Append n.
9999999999999999n
JavaScript
// 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
Not a Number
Result of an invalid numeric operation. Uniquely, NaN !== NaN is always true.
Infinity
Positive Infinity
Produced by dividing a positive number by zero or exceeding the maximum float.
-Infinity
Negative Infinity
Produced by dividing a negative number by zero, or -Infinity directly.
JavaScript — Special Values
// 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)
Watch out
Always use 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…).

0.1 + 0.2 0.30000000000000004 Binary can't represent 0.1 exactly
1.005.toFixed(2) "1.00" Rounds incorrectly due to float storage
0.1 + 0.2 === 0.3 false Never compare floats with ===
Math.abs(0.1+0.2-0.3) < Number.EPSILON true Correct way — use epsilon tolerance
+(0.1 + 0.2).toFixed(1) 0.3 Round then convert back to number
JavaScript — Handling Precision
// 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
Tip
For financial calculations where precision is critical (currency, taxes), use integer arithmetic (store amounts in cents) or a dedicated library like 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
JavaScript — Number Methods
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
⚡
Free Resource
Download our JavaScript Cheat Sheet
Number methods, Math utilities & BigInt — all on one page.
Get Sheet

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().

Note
All 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.PI
3.14159265358979…
Ratio of a circle's circumference to its diameter.
Math.E
2.71828182845904…
Euler's number — base of the natural logarithm.
Math.SQRT2
1.41421356237309…
Square root of 2.
Math.LN2
0.69314718055994…
Natural logarithm of 2.
Math.LN10
2.30258509299404…
Natural logarithm of 10.
Math.LOG2E
1.44269504088896…
Base-2 logarithm of E.

Math Methods

These are the most commonly used methods on the Math object, grouped by category:

Math.round(x)
Rounds to the nearest integer. .5 rounds up.
Math.round(4.6) → 5
Math.floor(x)
Rounds down to the nearest integer (towards −∞).
Math.floor(4.9) → 4
Math.ceil(x)
Rounds up to the nearest integer (towards +∞).
Math.ceil(4.1) → 5
Math.trunc(x)
Removes the decimal part (truncates towards zero). Unlike floor for negatives.
Math.trunc(-4.9) → -4
Math.abs(x)
Returns the absolute (positive) value of a number.
Math.abs(-7) → 7
Math.pow(base, exp)
Returns base raised to exp. Equivalent to base ** exp.
Math.pow(2, 8) → 256
Math.sqrt(x)
Returns the square root. Returns NaN for negative input.
Math.sqrt(144) → 12
Math.cbrt(x)
Returns the cube root of a number.
Math.cbrt(27) → 3
Math.max(...values)
Returns the largest of zero or more numbers.
Math.max(3, 9, 1) → 9
Math.min(...values)
Returns the smallest of zero or more numbers.
Math.min(3, 9, 1) → 1
Math.random()
Returns a pseudo-random float in [0, 1). Combine with floor for integer ranges.
Math.random() → 0.472…
Math.sign(x)
Returns 1, -1, or 0 depending on the sign of the number.
Math.sign(-5) → -1
Math.log(x)
Returns the natural logarithm (base e) of a number.
Math.log(Math.E) → 1
Math.log2(x) / Math.log10(x)
Returns the base-2 or base-10 logarithm of a number.
Math.log2(8) → 3
Math.hypot(...values)
Returns the square root of the sum of squares — Euclidean distance formula.
Math.hypot(3, 4) → 5
Math.clz32(x)
Counts leading zero bits in the 32-bit binary representation.
Math.clz32(1) → 31
JavaScript — Math in Practice
// ── 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.

Live Editor
✎ Editor
👁 Preview

Common Patterns & Recipes

These are everyday number utilities you'll find yourself writing repeatedly in real projects:

JavaScript — Useful Recipes
// ── 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)); // 55


Quick Check
What does typeof NaN return in JavaScript?
Quick Check
Which method returns a random integer between 1 and 10 (inclusive)?
Chapter Summary
  • 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 global isNaN() — to check for NaN safely.
  • Float comparison with === is unreliable — use Number.EPSILON tolerance or .toFixed() for display.
  • Key number methods: toFixed(), parseInt(), parseFloat(), and Number.isInteger().
  • Math is 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

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel