# How to Round to 2 Decimal Places in JavaScript [4 Ways]

Here are the four ways to round to 2 decimal places in JavaScript:

1. Using toFixed()
2. Using Math.round()
3. Using .toPrecision()
4. Using custom method

## Method 1: Using the toFixed()

The “toFixed()” method accepts an argument that specifies the number of decimal places you want to round to and returns a “string” representing the rounded number.

``````const num = 3.141592;
const roundedNum = num.toFixed(2);

console.log(roundedNum);
``````

Remember that the “toFixed()” method returns a string, not a number. If you need the result as a number, you can convert it back to a number using “parseFloat()” or the “unary plus operator (+)”.

``````const num = 3.141592;
const roundedNum = num.toFixed(2);

const numAsFloat = parseFloat(roundedNum);
console.log(numAsFloat);

const numAsNumber = +roundedNum;
console.log(numAsNumber);
``````

Output

``````3.14
3.14
``````

## Method 2: Using Math.round()

Use Math.round() and multiply the number by 100, round it to the nearest integer, and divide the result by 100.

``````const num = 3.141592;
const roundedNum = Math.round(num * 100) / 100;

console.log(roundedNum);
``````

Output

``````3.14
``````

## Method 3: Using the .toPrecision method

The .toPrecision() method formats a number to a specified length. However, it’s worth noting that the length includes the digits before the decimal point, so it may not be definitive for simply rounding to a fixed number of decimal places. But you can still make it work for that purpose.

``````const num = 123.456789;

const roundedNum = parseFloat(num.toPrecision(5));

console.log(roundedNum);
``````

Output

`123.46`

## Method 4: Using a Custom Method

You can create a custom method to round a number to a specific number of decimal places. This is often done using the following formula:

Here’s how you can implement this in JavaScript:

``````function roundToDecimalPlaces(num, decimalPlaces) {
const factor = Math.pow(10, decimalPlaces);
return Math.round(num * factor) / factor;
}

const num = 123.456789;
const roundedNum = roundToDecimalPlaces(num, 2);

console.log(roundedNum);``````

Output

``````123.46
``````

Here’s another custom method to round to 2 decimal places in JS.

``````function roundToTwoDecimalPlaces(num) {
return Math.round((num + Number.EPSILON) * 100) / 100;
}

const num = 123.456;
const roundedNum = roundToTwoDecimalPlaces(num);
console.log(roundedNum);``````

Output

``````123.46
``````

That’s it!