JavaScript Functions and Methods: A Topic-by-Topic Reference · Lesson 2 of 12

Lesson 2: Number and Math

Math.round, floor, ceil, trunc, abs, max, min, pow, sqrt, random, hypot, sign, and floating-point precision.

Lesson 2: Number and Math

Math is a built-in object with maths functions: no new, no import. All JavaScript numbers are 64-bit decimals, which matters for precision.

Rounding

Math.round(x), floor(x), ceil(x), trunc(x)

Nearest, down, up, and cut off the decimals. Compare them on negative numbers.

for (const x of [2.5, 2.4, -2.5, -2.4]) {
  console.log(x, Math.round(x), Math.floor(x), Math.ceil(x), Math.trunc(x));
}

Output:

2.5 3 2 3 2
2.4 2 2 3 2
-2.5 -2 -3 -2 -2
-2.4 -2 -3 -2 -2

Rounding to decimals

Math.round works on whole numbers, so scale first.

const round2 = (n) => Math.round(n * 100) / 100;
console.log(round2(3.14159));
console.log(Math.round(1234.5678 * 10) / 10);

Output:

3.14
1234.6

Powers and roots

Math.pow(a, b), **, sqrt, cbrt, hypot

Power, square root, cube root, and the hypotenuse.

console.log(Math.pow(2, 10), 2 ** 10);
console.log(Math.sqrt(144), Math.cbrt(27));
console.log(Math.hypot(3, 4));

Output:

1024 1024
12 3
5

Math.log, log2, log10, exp

Logarithms and e to a power.

console.log(Math.log10(1000), Math.log2(8));
console.log(Math.log(Math.E));
console.log(Math.exp(0));

Output:

3 3
1
1

Comparing and limiting

Math.max(...), Math.min(...)

Take separate numbers; spread an array into them with ....

console.log(Math.max(4, 9, 2), Math.min(4, 9, 2));
const nums = [5, 1, 8];
console.log(Math.max(...nums));
console.log(Math.max());

Output:

9 2
8
-Infinity

Clamping a value

Keep a number between a minimum and a maximum.

const clamp = (n, lo, hi) => Math.min(Math.max(n, lo), hi);
console.log(clamp(15, 0, 10), clamp(-3, 0, 10), clamp(5, 0, 10));

Output:

10 0 5

Math.abs(x) and Math.sign(x)

Absolute value, and -1, 0 or 1 by sign.

console.log(Math.abs(-7.5));
console.log(Math.sign(-9), Math.sign(0), Math.sign(4));

Output:

7.5
-1 0 1

Random numbers

Math.random()

A decimal from 0 up to (but not including) 1. The values change every run, so these examples are shown but not run.

console.log(Math.random());
const die = Math.floor(Math.random() * 6) + 1;       // 1 to 6
const between = (lo, hi) => Math.floor(Math.random() * (hi - lo + 1)) + lo;
console.log(die, between(10, 20));

Shuffling and picking at random

Pick a random item from an array (not run, because it is random).

const pick = (arr) => arr[Math.floor(Math.random() * arr.length)];
console.log(pick(["red", "green", "blue"]));

Trigonometry and constants

Math.PI, Math.E, sin, cos, tan

Angles are in radians: degrees x PI / 180.

console.log(Math.PI);
console.log(Math.sin(Math.PI / 6).toFixed(3));
const deg = (r) => (r * 180) / Math.PI;
console.log(deg(Math.PI));

Output:

3.141592653589793
0.500
180

Number constants and big numbers

Number.MAX_SAFE_INTEGER, EPSILON, Infinity

Limits of the number type.

console.log(Number.MAX_SAFE_INTEGER);
console.log(Number.EPSILON > 0);
console.log(1 / 0, -1 / 0, 0 / 0);

Output:

9007199254740991
true
Infinity -Infinity NaN

BigInt

Whole numbers of any size: add n to the number. You cannot mix BigInt and normal numbers.

console.log(2 ** 64);
console.log(2n ** 64n);
console.log(123456789012345678901234567890n * 2n);
console.log(typeof 10n);

Output:

18446744073709552000
18446744073709551616n
246913578024691357802469135780n
bigint

Floating-point precision

console.log(0.1 + 0.2);
console.log(0.1 + 0.2 === 0.3);
console.log(Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON);
console.log((0.1 * 3).toFixed(2));
console.log(Math.round(1.005 * 100) / 100);

Output:

0.30000000000000004
false
true
0.30
1

For money, store whole units (paisa) as integers and divide only when displaying. Never compare decimals with ===; compare their difference to a small tolerance.

Try it yourself

  1. Write average(numbers) using reduce (Lesson 6) and round it to 2 decimals.
  2. Write a function that returns a random whole number between two values, inclusive.
  3. Find the distance between two points (x1, y1) and (x2, y2) with Math.hypot.

Next lesson: String methods, part 1.

Finished this lesson?Log in to save your progress and pick up where you left off.
Next lesson →

Comments

Loading comments…

MeroSir Team
A free MeroSir course. Run the examples yourself and try the exercises: you learn programming by doing. Spotted a mistake? Use the Report button above the lesson.
Lesson 2: Number and Math | MeroSir