JavaScript for impatient programmers (ES2021 edition)
Please support this book: buy it or donate
(Ad, please don’t block.)

17 Math



Math is an object with data properties and methods for processing numbers. You can see it as a poor man’s module: It was created long before JavaScript had modules.

17.1 Data properties

17.2 Exponents, roots, logarithms

17.3 Rounding

Rounding means converting an arbitrary number to an integer (a number without a decimal fraction). The following functions implement different approaches to rounding.

Tbl. 12 shows the results of the rounding functions for a few representative inputs.

Table 12: Rounding functions of Math. Note how things change with negative numbers because “larger” always means “closer to positive infinity”.
-2.9 -2.5 -2.1 2.1 2.5 2.9
Math.floor -3 -3 -3 2 2 2
Math.ceil -2 -2 -2 3 3 3
Math.round -3 -2 -2 2 3 3
Math.trunc -2 -2 -2 2 2 2

17.4 Trigonometric Functions

All angles are specified in radians. Use the following two functions to convert between degrees and radians.

function degreesToRadians(degrees) {
  return degrees / 180 * Math.PI;
}
assert.equal(degreesToRadians(90), Math.PI/2);

function radiansToDegrees(radians) {
  return radians / Math.PI * 180;
}
assert.equal(radiansToDegrees(Math.PI), 180);

17.5 Various other functions

17.6 Sources