How To Round To 2 Decimal Places In Javascript

How To Round To 2 Decimal Places In Javascript


In javascript, learn how to round off a given number to two decimal points.

There are two ways in javascript to round a number up to two decimal places.

Method 1: Using the ToFixed() method, the fraction is converted to an integer and returned as a string.

Table of Contents

the toFixed() method

An integer between 0 and 20 can be used as the input value.

Input:
let a = 3.14159265359;
let b = a.toFixed(2);
console.log(b);

Output:
"3.14"

Based on the following numbers, it rounds to the nearest ceiling or floor value.

If it’s greater than 5, it’ll take the value of the ceiling; otherwise, it’ll take the value of the floor.

Method 2: In Javascript, round the number to two decimal places by utilizing

the Math.Round() method

The closest integer value is rounded up using the Math.round() method. The input is a number that needs to be rounded to the nearest whole number.

It is possible to round off a number to a specific number of decimal places using this formula: first, multiply the input number by the number of decimal places to be rounded off, which in this case is 2, and then divide the result by the number of decimal places to be rounded off (as in the example above).

An integer value is returned as the final outcome.

Input:
Math.round(3.14159265359 * 100) / 100

// Output:
3.14

You can now create your own custom function to round off any digit.

let roundOff = (num, places) => {
  const x = Math.pow(10,places);
  return Math.round(num * x) / x;
}
Input:
console.log(roundOff(3.14159265359, 2));

output:
3.14


About the author

Pretium lorem primis senectus habitasse lectus donec ultricies tortor adipiscing fusce morbi volutpat pellentesque consectetur risus molestie curae malesuada. Dignissim lacus convallis massa mauris enim mattis magnis senectus montes mollis phasellus.

Leave a Comment