How to Round a Number in JavaScript

Updated onbyAlan Morel
How to Round a Number in JavaScript

Rounding a number can be a useful thing to do when you want to display a number in a more readable format.

For example, sometimes showing an exact number is not necessary, and you can round it to the nearest whole number.

In this article, we will look at how to round a number in JavaScript.

Using Math.round()

The most straightforward way to round a number in JavaScript is to use the Math.round() function.

This function takes in a number and returns the nearest whole number.

First, let's define a variable called number and assign it the value of 3.14:

JAVASCRIPT
const number = 3.14;

Now, let's round this number using the Math.round() function:

JAVASCRIPT
const number = 3.14; const roundedNumber = Math.round(number); console.log(roundedNumber);
BASH
3

As you can see, the roundedNumber variable now has the value of 3 because 3.14 was rounded to the nearest whole number.

Using Math.ceil()

Another way to round a number in JavaScript is to use the Math.ceil() function.

This function takes in a number and returns the smallest whole number that is greater than or equal to the given number.

In other words, it rounds a number up to the nearest whole number.

Let's see how this works in practice.

JAVASCRIPT
const number = 3.14; const roundedNumber = Math.ceil(number); console.log(roundedNumber);
BASH
4

As mentioned before Math.ceil() rounds a number up to the nearest whole number so 3.14 was rounded up to 4.

Using Math.floor()

The Math.floor() function is similar to Math.ceil() but it rounds a number down to the nearest whole number.

Let's see an example of this:

JAVASCRIPT
const number = 3.14; const roundedNumber = Math.floor(number); console.log(roundedNumber);
BASH
3

No surprises here, 3.14 was rounded down to 3.

Conclusion

In this article, we looked at how to round a number in JavaScript.

Your options include using the Math.round() function, Math.ceil() function, or Math.floor() function.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.