How to Round to 2 Decimal Places in Javasacript

There’s a couple different ways to round to two decimal places in Javascript. Which one you use will depend on your situation.

Use Math.round

The best way to do this is using Math.round, especially if you still need a number on the other end to do math on.

Here is the most accurate and correct way to do it:

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

const pi = 3.14159265359;
const roundedPi = roundToTwoDecimalPlaces(pi);

// -> 3.14
console.log(typeof roundedPi);
// -> Number

What is Number.EPSILON?

Number.EPSILON is a static data property of the Number object in JavaScript, which represents the difference between 1 and the smallest floating point number greater than 1.

Why are we adding it to the number?

It prevents errors when rounding small numbers. How / why? I read the documentation but still have no idea. Here, see if you can figure it out:

Use toFixed

This appears to be the easiest way at a glance, but there’s a caveat: the number you round will be returned as a string, not a float. So, if you need to do any further math on the number, you won’t be able to until you convert it back.

Here’s how you use it:

const num1 = 2.455;
// -> 2.46

const num2= 2.4;
// -> 2.40

Warning! The result of this function is a string not a float!

What if I still need a number?

You can convert it back to a number by using the parseFloat function built in to Javascript:

const num = 2.455;
const roundedNum = num.toFixed(2);

// -> 2.46
console.log(typeof roundedNum);
// -> string

// Convert it back to a floating point
const roundedNumFloat = parseFloat(roundedNum);

// -> 2.46
console.log(typeof roundedNumFloat);
// -> number

Here’s a function using this method that you can copy/paste:

function roundToTwoDecimalPlaces(num) {
    return parseFloat(num.toFixed(2))