HomepageExploring JavaScript (ES2024 Edition)
You can support this book: buy it or donate
(Ad, please don’t block.)

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

19.1 Data properties

19.2 Exponents, roots, logarithms

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

Table 19.1 shows the results of the rounding functions for a few representative inputs.

-2.9-2.5-2.12.12.52.9
Math.floor-3-3-3222
Math.ceil-2-2-2333
Math.round-3-2-2233
Math.trunc-2-2-2222

Table 19.1: Rounding functions of Math. Note how things change with negative numbers because “larger” always means “closer to positive infinity”.

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

19.5 Various other functions

19.6 Sources