JavaScript Round a Number to n decimal places

In this short tutorial, you will learn how to round off a given number to n decimal places in JavaScript.

Solution #1 – Using toFixed() Method

toFixed() method rounds off to nearest ceiling or flooring value based on the later digits.

Input:

let a = 3.2846;
let b = a.toFixed(2);
let c = a.toFixed(3);

Output:

b: "3.28"
c: "3.285"

Tested in Chrome console:

Solution #2 – Using Math.round() Method

The Math.round() method is used to round to the nearest integer value.
To round off any number to n decimal place we can first multiply the input number with “10 to the Nth power“, e.g inputNum * Math.pow(10, n);
Then use Math.round() method to round the above multiplied number and then divide it by “10 to the Nth power“.

Input:

let a = 3.2846;
let b = Math.round(a * Math.pow(10,2)) / Math.pow(10,2);
let c = Math.round(a * Math.pow(10,3)) / Math.pow(10,3);

Output:

b: 3.28
c: 3.285

Tested in Chrome console:

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.