JS

Numbers & Math

JavaScript · 9 entries

Parsing Numbers

syntax
Number(value)
parseInt(string, radix)
parseFloat(string)
example
console.log(Number("42"));        // 42
console.log(Number("3.14abc"));   // NaN
console.log(parseInt("3.14abc")); // 3
console.log(parseFloat("3.14abc")); // 3.14
console.log(parseInt("ff", 16));  // 255

Note Number() is stricter -- rejects partially numeric strings. parseInt() stops at the first non-numeric character. Always pass the radix to parseInt() to avoid octal surprises.

Number Checking

syntax
Number.isNaN(value)
Number.isFinite(value)
Number.isInteger(value)
Number.isSafeInteger(value)
example
console.log(Number.isNaN(NaN));          // true
console.log(Number.isNaN("hello"));      // false
console.log(isNaN("hello"));             // true (!) 
console.log(Number.isInteger(4.0));       // true
console.log(Number.isSafeInteger(2**53)); // false

Note Always use Number.isNaN() over the global isNaN(). The global version coerces its argument to a number first, giving misleading results.

Rounding

syntax
Math.round(n) | Math.floor(n) | Math.ceil(n) | Math.trunc(n)
example
const price = 19.872;
console.log(Math.round(price));  // 20
console.log(Math.floor(price));  // 19
console.log(Math.ceil(price));   // 20
console.log(Math.trunc(price));  // 19
console.log(Math.trunc(-3.7));   // -3 (not -4)

Note trunc() simply removes decimals (towards zero). floor() rounds towards negative infinity. They differ for negative numbers: floor(-3.2) = -4 but trunc(-3.2) = -3.

Formatting Decimals

syntax
num.toFixed(digits)
num.toPrecision(precision)
example
const total = 29.5;
console.log(total.toFixed(2));       // "29.50"
console.log((0.1 + 0.2).toFixed(2)); // "0.30"

const big = 123456.789;
console.log(big.toPrecision(6));     // "123457"

Note toFixed() returns a STRING, not a number. Wrap in Number() or use + to convert back: +total.toFixed(2)

Random Numbers

syntax
Math.random()  // [0, 1)
example
// Random float between 0 and 1
console.log(Math.random());

// Random integer from min to max (inclusive)
function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomInt(1, 100));

Note Math.random() is NOT cryptographically secure. For tokens or passwords, use crypto.getRandomValues() or crypto.randomUUID().

Min, Max, and Clamping

syntax
Math.min(...values)
Math.max(...values)
example
const scores = [88, 45, 99, 72, 61];
console.log(Math.min(...scores)); // 45
console.log(Math.max(...scores)); // 99

// Clamp a value between bounds
function clamp(value, min, max) {
  return Math.min(Math.max(value, min), max);
}
console.log(clamp(150, 0, 100)); // 100

Note For very large arrays (100k+ elements), spread can cause a stack overflow. Use a reduce loop instead.

BigInt

syntax
const big = 123n;
const big = BigInt(value);
example
const huge = 9007199254740993n;
console.log(huge + 1n);   // 9007199254740994n
console.log(huge * 2n);   // 18014398509481986n

// Convert between types
console.log(Number(100n)); // 100
console.log(BigInt(42));   // 42n

Note Cannot mix BigInt and Number in arithmetic (throws TypeError). Convert one type first. No Math methods work with BigInt.

Powers and Roots

syntax
base ** exponent
Math.sqrt(n)
Math.cbrt(n)
Math.pow(base, exp)
example
console.log(2 ** 10);         // 1024
console.log(Math.sqrt(144));  // 12
console.log(Math.cbrt(27));   // 3
console.log(Math.abs(-42));   // 42

Note The ** operator is cleaner than Math.pow() and works with BigInt too: 2n ** 64n.

Locale Number Formatting

syntax
new Intl.NumberFormat(locale, options).format(n)
example
const price = 1234567.89;
console.log(new Intl.NumberFormat("en-US", {
  style: "currency", currency: "USD"
}).format(price));
// "$1,234,567.89"

console.log(new Intl.NumberFormat("de-DE").format(price));
// "1.234.567,89"

Note Intl.NumberFormat handles thousands separators, currency symbols, percentages, and units correctly for any locale.