JavaScript

Round to 2 decimal places in JavaScript

In this tutorial, we are going to see how to round to 2 digits after the decimal point. A number can be rounded to a maximum of 2 decimal places using two different approaches in javascript.
 

Method 1: Using the Number.toFixed() method

The Number.toFixed() method takes an integer as input and returns the number as a string. The whole number is between 0 and 20.

let x = 2.960024578;
let res = x.toFixed(2);
console.log(res);

Output:

"2.96"

 

 

Method 2: Using the Math.round() method

The Math.round() method is used to round to the nearest integer value. We can use this method by multiplying the number by 10 ^ 2 = 100 (2 decimal places), then divide it by 10 ^ 2 = 100.

let x = 2.960024578;
let res = Math.round(x * 100) / 100
console.log(res);

Output:

"2.96"
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *