Numbers and Math
JavaScript has a single number type (all numbers are 64-bit floating point). The Math object provides mathematical functions and constants for advanced calculations.
Number Type Basics
All numbers in JavaScript are floating point (decimals):
const integer = 42;
const decimal = 3.14159;
const negative = -10;
const scientific = 2.5e6; // 2.5 × 10^6 = 2,500,000
console.log(typeof 42); // "number"
console.log(typeof 3.14); // "number"
console.log(typeof -10); // "number"
Special Number Values
// Infinity
console.log(1 / 0); // Infinity
console.log(-1 / 0); // -Infinity
console.log(Infinity); // Infinity
// NaN (Not a Number)
console.log(0 / 0); // NaN
console.log('text' - 5); // NaN
console.log(Math.sqrt(-1)); // NaN
Parsing Strings to Numbers
parseInt() - Parse to Integer
console.log(parseInt('42')); // 42
console.log(parseInt('42.99')); // 42 (drops decimal)
console.log(parseInt(' 42 ')); // 42 (trims whitespace)
console.log(parseInt('42 years')); // 42 (stops at non-digit)
// ❌ Invalid
console.log(parseInt('hello')); // NaN
console.log(parseInt('abc123')); // NaN
parseInt() with Radix (Base)
// Binary (base 2)
console.log(parseInt('1010', 2)); // 10
// Octal (base 8)
console.log(parseInt('77', 8)); // 63
// Hexadecimal (base 16)
console.log(parseInt('FF', 16)); // 255
console.log(parseInt('A5', 16)); // 165
// Always specify radix for clarity
console.log(parseInt('10', 10)); // 10 (decimal)
parseFloat() - Parse to Decimal
console.log(parseFloat('3.14')); // 3.14
console.log(parseFloat('3.14159')); // 3.14159
console.log(parseFloat(' 2.5 ')); // 2.5
console.log(parseFloat('2.5 meters')); // 2.5
// Scientific notation
console.log(parseFloat('2.5e6')); // 2500000
console.log(parseFloat('1.23e-4')); // 0.000123
Number() - Convert to Number
console.log(Number('42')); // 42
console.log(Number('3.14')); // 3.14
console.log(Number(' 10 ')); // 10
console.log(Number(true)); // 1
console.log(Number(false)); // 0
console.log(Number(null)); // 0
console.log(Number(undefined)); // NaN
console.log(Number('hello')); // NaN
console.log(Number('42px')); // NaN (stricter than parseInt!)
Comparison
const str = '42.5px';
console.log(parseInt(str)); // 42 (stops at non-digit)
console.log(parseFloat(str)); // 42.5 (stops at non-digit)
console.log(Number(str)); // NaN (all or nothing)
Number Methods
toFixed() - Fixed Decimal Places
const pi = 3.14159;
console.log(pi.toFixed(2)); // "3.14" (string!)
console.log(pi.toFixed(4)); // "3.1416" (rounds)
console.log(pi.toFixed(0)); // "3"
// Money formatting
const price = 29.9;
console.log('$' + price.toFixed(2)); // "$29.90"
// Convert back to number
const rounded = parseFloat(pi.toFixed(2)); // 3.14
toPrecision() - Total Significant Digits
const num = 123.456;
console.log(num.toPrecision(4)); // "123.5" (4 total digits)
console.log(num.toPrecision(2)); // "1.2e+2" (scientific notation)
console.log(num.toPrecision(6)); // "123.456"
const small = 0.000123;
console.log(small.toPrecision(2)); // "0.00012"
toString() - Convert to String
const num = 42;
console.log(num.toString()); // "42"
console.log(num.toString(2)); // "101010" (binary)
console.log(num.toString(8)); // "52" (octal)
console.log(num.toString(16)); // "2a" (hexadecimal)
const hex = 255;
console.log(hex.toString(16)); // "ff"
toExponential() - Scientific Notation
const big = 123456;
console.log(big.toExponential()); // "1.23456e+5"
console.log(big.toExponential(2)); // "1.23e+5"
const small = 0.000123;
console.log(small.toExponential()); // "1.23e-4"
Checking Number Values
Number.isInteger() - Is Whole Number?
console.log(Number.isInteger(42)); // true
console.log(Number.isInteger(42.0)); // true
console.log(Number.isInteger(42.5)); // false
console.log(Number.isInteger('42')); // false (string)
console.log(Number.isInteger(NaN)); // false
console.log(Number.isInteger(Infinity)); // false
Number.isFinite() - Is Finite Number?
console.log(Number.isFinite(42)); // true
console.log(Number.isFinite(3.14)); // true
console.log(Number.isFinite(Infinity)); // false
console.log(Number.isFinite(-Infinity));// false
console.log(Number.isFinite(NaN)); // false
console.log(Number.isFinite('42')); // false (strict, doesn't convert)
Number.isNaN() - Is NaN?
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN(42)); // false
console.log(Number.isNaN('hello')); // false (doesn't convert)
console.log(Number.isNaN(0 / 0)); // true
// Difference from global isNaN()
console.log(isNaN('hello')); // true (converts first)
console.log(Number.isNaN('hello')); // false (strict)
isNaN() - Global Version (Less Strict)
console.log(isNaN(NaN)); // true
console.log(isNaN('hello')); // true (converts to NaN first)
console.log(isNaN('42')); // false (converts to 42)
console.log(isNaN(undefined)); // true (converts to NaN)
// Prefer Number.isNaN() for strict checking
Math Object
The Math object provides mathematical constants and functions:
Math Constants
console.log(Math.PI); // 3.141592653589793
console.log(Math.E); // 2.718281828459045 (Euler's number)
console.log(Math.LN2); // 0.6931471805599453 (natural log of 2)
console.log(Math.LN10); // 2.302585092994046
console.log(Math.SQRT2); // 1.4142135623730951
Math.round() - Round to Nearest Integer
console.log(Math.round(4.3)); // 4
console.log(Math.round(4.5)); // 5
console.log(Math.round(4.7)); // 5
console.log(Math.round(-4.3)); // -4
console.log(Math.round(-4.5)); // -4 (rounds toward zero)
console.log(Math.round(-4.7)); // -5
Math.floor() - Round Down
console.log(Math.floor(4.9)); // 4
console.log(Math.floor(4.1)); // 4
console.log(Math.floor(-4.1)); // -5 (toward negative infinity)
console.log(Math.floor(-4.9)); // -5
Math.ceil() - Round Up
console.log(Math.ceil(4.1)); // 5
console.log(Math.ceil(4.9)); // 5
console.log(Math.ceil(-4.9)); // -4 (toward positive infinity)
console.log(Math.ceil(-4.1)); // -4
Math.trunc() - Remove Decimal Part
console.log(Math.trunc(4.9)); // 4
console.log(Math.trunc(4.1)); // 4
console.log(Math.trunc(-4.9)); // -4 (just removes decimal)
console.log(Math.trunc(-4.1)); // -4
Math.abs() - Absolute Value
console.log(Math.abs(5)); // 5
console.log(Math.abs(-5)); // 5
console.log(Math.abs(-3.14)); // 3.14
console.log(Math.abs(0)); // 0
Math.min() and Math.max()
console.log(Math.min(1, 2, 3)); // 1
console.log(Math.min(5, -10, 15)); // -10
console.log(Math.max(1, 2, 3)); // 3
console.log(Math.max(5, -10, 15)); // 15
// With arrays (use spread operator)
const numbers = [1, 5, 3, 9, 2];
console.log(Math.min(...numbers)); // 1
console.log(Math.max(...numbers)); // 9
Math.pow() - Power
console.log(Math.pow(2, 3)); // 8 (2³)
console.log(Math.pow(5, 2)); // 25 (5²)
console.log(Math.pow(10, -2)); // 0.01 (10⁻²)
// Modern alternative: ** operator
console.log(2 ** 3); // 8
console.log(5 ** 2); // 25
Math.sqrt() - Square Root
console.log(Math.sqrt(9)); // 3
console.log(Math.sqrt(16)); // 4
console.log(Math.sqrt(2)); // 1.4142135623730951
console.log(Math.sqrt(-1)); // NaN (no complex numbers)
Math.cbrt() - Cube Root
console.log(Math.cbrt(8)); // 2 (∛8)
console.log(Math.cbrt(27)); // 3
console.log(Math.cbrt(-8)); // -2 (works with negatives)
Math.random() - Random Numbers
Generates random number between 0 (inclusive) and 1 (exclusive):
console.log(Math.random()); // 0.123456789 (example)
console.log(Math.random()); // 0.987654321 (different each time)
Random Integer in Range
// Random integer between min (inclusive) and max (exclusive)
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
console.log(randomInt(1, 7)); // 1-6 (dice roll)
console.log(randomInt(0, 100)); // 0-99
// Random integer between min and max (both inclusive)
function randomIntInclusive(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomIntInclusive(1, 6)); // 1-6 (dice roll)
console.log(randomIntInclusive(1, 10)); // 1-10
Random from Array
const colors = ['red', 'green', 'blue', 'yellow'];
const randomColor = colors[Math.floor(Math.random() * colors.length)];
console.log(randomColor); // Random color from array
Random Boolean
const randomBool = Math.random() < 0.5;
console.log(randomBool); // true or false (50% each)
Common Number Calculations
1. Percentage
function percentage(value, total) {
return (value / total) * 100;
}
console.log(percentage(75, 100)); // 75
console.log(percentage(3, 4)); // 75
console.log(percentage(1, 3).toFixed(2)); // "33.33"
2. Average
function average(...numbers) {
const sum = numbers.reduce((a, b) => a + b, 0);
return sum / numbers.length;
}
console.log(average(10, 20, 30)); // 20
console.log(average(85, 90, 78, 92)); // 86.25
3. Clamp (Limit to Range)
function clamp(value, min, max) {
return Math.min(Math.max(value, min), max);
}
console.log(clamp(5, 0, 10)); // 5 (within range)
console.log(clamp(-5, 0, 10)); // 0 (clamped to min)
console.log(clamp(15, 0, 10)); // 10 (clamped to max)
4. Round to Decimal Places
function roundTo(num, decimals) {
return Math.round(num * 10 ** decimals) / 10 ** decimals;
}
console.log(roundTo(3.14159, 2)); // 3.14
console.log(roundTo(2.5, 0)); // 3
console.log(roundTo(1.005, 2)); // 1.01
5. Distance Between Points
function distance(x1, y1, x2, y2) {
const dx = x2 - x1;
const dy = y2 - y1;
return Math.sqrt(dx ** 2 + dy ** 2);
}
console.log(distance(0, 0, 3, 4)); // 5
console.log(distance(1, 1, 4, 5)); // 5
6. Circle Area
function circleArea(radius) {
return Math.PI * radius ** 2;
}
console.log(circleArea(5).toFixed(2)); // "78.54"
console.log(circleArea(10).toFixed(2)); // "314.16"
Best Practices
✅ DO:
// Use toFixed() for money
const price = 29.995;
console.log('$' + price.toFixed(2)); // "$30.00"
// Use Number.isInteger() to check integers
if (Number.isInteger(userInput)) {
// Process integer
}
// Use Math methods for calculations
const max = Math.max(...scores);
const average = scores.reduce((a, b) => a + b) / scores.length;
// Specify radix in parseInt()
const num = parseInt(userInput, 10);
// Use strict checking
if (Number.isNaN(value)) {
// Handle NaN
}
❌ DON’T:
// Don't compare floats directly
if (0.1 + 0.2 === 0.3) { // false!
// Won't run
}
// Don't forget to convert strings
const result = '5' + 3; // '53' (oops!)
// Don't use global isNaN() when you mean Number.isNaN()
isNaN('hello'); // true (converts first - confusing)
// Don't divide by zero without checking
const result = total / count; // Could be Infinity!
// Don't use imprecise rounding
const rounded = Math.round(price * 100) / 100; // Can have errors
// Use toFixed() instead
Summary
Parsing:
parseInt(str, radix)- Parse to integerparseFloat(str)- Parse to decimalNumber(str)- Strict conversion
Number Methods:
toFixed(decimals)- Format with fixed decimalstoPrecision(digits)- Total significant digitstoString(radix)- Convert to string (with base)
Checking:
Number.isInteger(n)- Is whole number?Number.isFinite(n)- Is finite?Number.isNaN(n)- Is NaN?
Math Object:
Math.round/floor/ceil/trunc()- RoundingMath.abs()- Absolute valueMath.min/max()- Min/max valuesMath.pow/sqrt/cbrt()- Powers and rootsMath.random()- Random 0-1Math.PI,Math.E- Constants
Random Integer (1-6):
Math.floor(Math.random() * 6) + 1
Next Article: Type Coercion