Open In App

How to Round a Number to a Certain Number of Decimal Places in JavaScript ?

Last Updated : 15 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, you can round a number to a certain number of decimal places using various methods, such as toFixed(), Math.round(), Math.floor(), Math.ceil(), or by using the Number.prototype.toFixed() method. Here’s how you can achieve it using these methods:

Using toFixed() method:

The toFixed() method returns a string representing the number rounded to a specified number of decimal places.

const num = 3.14159;
// Rounds to 2 decimal places
const roundedNum = num.toFixed(2);
console.log(roundedNum); // Output: "3.14"

Using Math.round():

The Math.round() method rounds a number to the nearest integer.

const num = 3.14159;
// Rounds to 2 decimal places
const roundedNum = Math.round(num * 100) / 100;
console.log(roundedNum); // Output: 3.14

Using Math.floor():

The Math.floor() method rounds a number down to the nearest integer.

const num = 3.14159;
// Rounds down to 2 decimal places
const roundedNum = Math.floor(num * 100) / 100;
console.log(roundedNum); // Output: 3.14

Using Math.ceil():

The Math.ceil() method rounds a number up to the nearest integer.

const num = 3.14159;
// Rounds up to 2 decimal places
const roundedNum = Math.ceil(num * 100) / 100;
console.log(roundedNum); // Output: 3.15

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads