Chapter 16. Math

This chapter describes JavaScript’s built-in Math object, which contains math functions commonly encountered in application development (if you are doing sophisticated numeric analysis, you may have to find third-party libraries).

Before we delve into the library, let’s remind ourselves how JavaScript handles numbers. In particular, there’s no dedicated integer class; all numbers are IEEE 754 64-bit floating-point numbers. For most functions in the math library, this simplifies things: a number is a number. While no computer will ever be able to fully represent an arbitrary real number, for practical purposes, you can think of JavaScript numbers as real numbers. Note that there’s no built-in support for complex numbers in JavaScript. If you need complex numbers, bignums, or more sophisticated structures or algorithms, I recommend starting with Math.js.

Outside of some basics, this chapter is not designed to teach you math; that’s a book (or 2 or 10) of its own.

Throughout the code comments in this chapter, I will use a tilde (~) prefix to indicate that a given value is approximate. I will also refer to properties of the Math object as functions, not methods. While they are technically static methods, the distinction is academic here, as the Math object provides namespacing, not context.

Formatting Numbers

A common need is to format numbers; that is, instead of displaying 2.0093, you want to display 2.1. Or instead of displaying 1949032, you want to display 1,949,032. ...

Get Learning JavaScript, 3rd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.