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

16 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.

16.1 Data properties

16.2 Exponents, roots, logarithms

16.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

16.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);

16.5 Various other functions

16.6 Sources