Table of Contents
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:
JAVASCRIPTconst number = 3.14;
Now, let's round this number using the Math.round() function:
JAVASCRIPTconst number = 3.14;
const roundedNumber = Math.round(number);
console.log(roundedNumber);
BASH3
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.
JAVASCRIPTconst number = 3.14;
const roundedNumber = Math.ceil(number);
console.log(roundedNumber);
BASH4
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:
JAVASCRIPTconst number = 3.14;
const roundedNumber = Math.floor(number);
console.log(roundedNumber);
BASH3
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!
Getting Started with TypeScript
How to Install Node on Windows, macOS and Linux
Managing PHP Dependencies with Composer
Getting Started with Svelte
Getting Started with Express
How to Serve Static Files with Nginx and Docker
How to Set Up Cron Jobs in Linux
Best Visual Studio Code Extensions for 2022
How to deploy a PHP app using Docker
How to deploy a Deno app using Docker
Using Puppeteer and Jest for End-to-End Testing
Getting User Location using JavaScript's Geolocation API
