Rounding numbers in JavaScript

Reading Time: < 1 minute 🕑

Last updated: July 4, 2022.

Basic rounding methods are available on the in-built Math object. For rounding to a fixed number of decimal points, the toFixed() method is available on numeric data.

Table of contents

Rounding to an integer value

Round to nearest integer with Math.round()

To round a number to its nearest integer value, use the Math.round() method:

Math.round(10.2); // 10
Math.round(1.5); // 2
Math.round(-7.2); // -7

// null and Boolean values are coerced to a number!
Math.round("abc"); // NaN
Math.round(null); // 0
Math.round(false); // 0
Math.round(true); // 1

Rounding up with Math.ceil()

Math.ceil() rounds up to the nearest integer:

Math.ceil(10.2); // 11
Math.ceil(3); // 3
Math.ceil(-5.9); // -5

Math.ceil(null); // 0
Math.ceil(false); // 0

Rounding down with Math.floor()

Math.floor() rounds down:

Math.floor(10.2); // 10
Math.floor(3); // 3
Math.floor(-5.9); // -6

Math.floor(null); // 0
Math.floor(false); // 0

Rounding to a fixed number of decimal places

Applying the toFixed() method to a numeric value will round it to a given number of decimal places.

The output is of type string. You can convert it back to a numeric value with Number().

const value = 5.2431;

let a = value.toFixed(0);
let b = value.toFixed(2);
let c = value.toFixed(4);

console.log(typeof a, typeof b, typeof c); // "string", "string", "string"

Number(a); // 5
Number(b); // 5.24
Number(c); // 5.2431

Related links