Math in JavaScript: rounding, comparing and random numbers

Math is a built-in object gathering the mathematical functions of JavaScript: rounding, minimum, maximum, powers and random numbers.
3 min read
Believemy logo

Math is not a class and is never instantiated. It is a toolbox left within reach, whose functions you call directly. On an ordinary web project, four or five of them cover every need.

The rest are worth knowing by name only: logarithms, trigonometry, roots. You look them up the day you need one, you do not memorize them.


Definition

Math is a built-in object exposing mathematical constants and functions. All its properties are static: you write Math.round(x), never new Math(), and the new operator actually throws on it.

JAVASCRIPT
console.log(Math.round(2.5));    // 3
console.log(Math.floor(2.9));    // 2, downward
console.log(Math.ceil(2.1));     // 3, upward
console.log(Math.trunc(-2.7));   // -2, drops the decimal part

console.log(Math.max(3, 9, 1));  // 9
console.log(Math.abs(-4));       // 4


The four ways to round

They look alike and disagree on negative numbers, which is the most common source of mistakes.

FunctionOn 2.5On -1.5Behavior
Math.round3-1Nearest, halves go up
Math.floor2-2Always downward
Math.ceil3-1Always upward
Math.trunc2-1Removes the decimal part

Math.round(-1.5) is -1 and not -2, because the rule is "upward" rather than "toward the larger absolute value". On durations or negative balances, this is exactly the kind of detail that shifts a total.

Good to know

These functions return a number, unlike toFixed which returns a string. To round to two decimals and stay numeric: Math.round(x * 100) / 100.


Random numbers

Math.random() returns a decimal between 0 inclusive and 1 exclusive. Every draw is built from there.

JAVASCRIPT
// An integer between 1 and 6
const die = Math.floor(Math.random() * 6) + 1;

// A random element from an array
const options = ["a", "b", "c"];
const pick = options[Math.floor(Math.random() * options.length)];

console.log(die, pick);

The Math.floor is essential: without it the index would be fractional and the array would return undefined. Note also that this draw is not cryptographic. For a security token you need crypto.randomUUID() or crypto.getRandomValues().


Frequently asked questions

Question

How do I find the maximum of an array?

Math.max expects separate arguments, not a list. So it has to be spread out with Spread (...): Math.max(...values). Be careful on an empty array, where the call returns -Infinity, which goes unnoticed until some display becomes inconsistent.


Question

Why is my two-decimal rounding sometimes wrong?

Because the starting number is already inexact. Math.round(1.005 * 100) / 100 gives 1 rather than 1.01, since 1.005 * 100 is actually a little under 100.5. The Number entry explains this floating point limit and the workaround, which is to work in whole numbers.


Question

Is there an operator for powers?

Yes, ** arrived in 2016 and does the same thing as Math.pow: 2 ** 10 and Math.pow(2, 10) both equal 1024. The operator reads better inside a formula, the function stays useful when the power is passed as an argument to something else.

Related terms

Discover our javaScript glossary

Every word of JavaScript explained simply: keywords, built-in objects, methods, errors and concepts. Clear definitions and examples that actually run, to learn and to troubleshoot.

Share this article

Want to help us? Share this article on your networks or even better: on your site, in an article or in your newsletter.