How to Round a Number in JavaScript
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!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Svelte
- Getting Started with Express
- Create an RSS Reader in Node
- Git Tutorial: Learn how to use Version Control
- How to deploy a .NET app using Docker
- How to build a Discord bot using TypeScript
- How to Scrape the Web using Node.js and Puppeteer
- Learn how to build a Slack Bot using Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up Stylus CSS Preprocessor
- Setting Up a Local Web Server using Node.js