How to round a number to 2 decimal places in JavaScript

Round a Number to 2 Decimal Places in JavaScript

The topic that will be covered in this article is how to round a number to 2 decimal places in JavaScript. We can do it in two ways: the toFixed() or Math. round() method.

Round a number to 2 decimal places in JavaScript

While programming Javascript, you may have to round a number to 2 decimal places, but you need to learn how to do this correctly. See the ways below.

Using toFixed() method

The number.toFixed() method preserves the user-specified decimal places when converting a number to a string type. The method will automatically add null values to produce the desired decimal length if the desired number of decimals is greater than the number that was passed.

Syntax:

number.toFixed(x)

Parameter:

  • x is the desired number of decimal places.

This is the most suitable method to do this. All you need to do is using it with a variable that contains decimal input, like the example below.

Code:

var number = 2.38473783;

// Use toFixed() method to round the number to 2 decimal places
var roundedNumber = number.toFixed(2);
console.log(roundedNumber);

Output:

2.38

With a parameter of two, you can get a number rounded to two decimal places. Let’s look at the output and see what it returns. That’s how this function works. Or you can also refer to the following method here. 

Using Math.round() method

The Math. round() method has a rounding function. The method will return the nearest integer to the number provided when calling the method. If a non-numeric value is provided, the method will return NaN.

Syntax:

Math.round( number)

Parameter:

  • Number: is the number to be rounded.

This way, we will round the number with the Math. round() function. First, we multiply the number by 100 to get the number with two decimal places and divide the decimal part by dividing the number by the “/” sign. Let’s see the following code to see how we code and how this method works with decimals.

Code:

var number = 2.38473783;

// Round the number and divide by the decimal
var roundedNumber = Math.round(number * 100) / 100;
console.log(roundedNumber);

When you use the Map. round() method, the number returned will lose the decimal part. You should pay attention to this. The return results of the two methods are the same. I wish you success with the methods mentioned in the article

Summary

In summary, the article has told you how to round a number to 2 decimal places in JavaScript. However, you should use the number.toFixed() method because it is built in to do this. Wish you a good day!

Maybe you are interested:

Leave a Reply

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