How to Round a Number to a Certain Number of Decimal Places in JavaScript ?
Last Updated :
15 Feb, 2024
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"
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
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
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
Please Login to comment...