HomepageExploring JavaScript (ES2025 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

19.3.1 Rounding to integer

Rounding to integer means converting an arbitrary number to an integer (a number without a decimal fraction). The following functions implement several approaches for doing so.

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.3.2 Rounding floats to 32 bits and 16 bits

19.3.2.1 Handling overflow and underflow

Math.f16round(x) rounds x to a 16-bit half-float (within a 64-bit double float).

If there is positive overflow (positive numbers being too far away from zero), the result is positive infinity:

> Math.f16round(2**15)
32768
> Math.f16round(2**16)
Infinity
> 2**16
65536

If there is negative overflow (negative numbers being too far away from zero), the result is negative infinity:

> Math.f16round(-(2**15))
-32768
> Math.f16round(-(2**16))
-Infinity
> -(2**16)
-65536

Arithmetic underflow means that a number has too many digits after a binary point (is too close to an integer). If that happens, digits that can’t be represented are omitted:

> Math.f16round(2**-24)
5.960464477539063e-8
> Math.f16round(2**-25)
0
> 2**-25
2.9802322387695312e-8

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