Round a Number to 2 Decimal Places | JavaScript

You can use:

Math.round((9.9876 + Number.EPSILON) * 100) / 100 //returns 9.99
Or
+9.9876.toFixed(2) //returns 9.99
But, it seems like Math.round() is a better solution, but it is not! In some cases it will NOT round correctly. Also, toFixed() will NOT round correctly in some cases.

Approximate Rounding

To correct the rounding problem with the previous Math.round() and toFixed(), you can define a custom rounding function that performs a "nearly equal" test to determine whether a fractional value is sufficiently close to a midpoint value to be subject to midpoint rounding.

The following function return the value of the given number rounded to the nearest integer accurately.

Number.prototype.roundTo = function(decimal) { return +(Math.round(this + "e+" + decimal) + "e-" + decimal); }
var num = 9.7654; console.log( num.roundTo(2));
Output:
9.77
Using the above function with halfway numbers, you will get either the upper rounded value as expected, or the lower rounded value sometimes depending on the input.

Using Number.toLocaleString()

The toLocaleString() method returns a string with a language-sensitive representation of the number. The following custom rounding function using Number.toLocaleString() return the value of the given number rounded to the nearest integer accurately.
const roundTo = (num, decimals) => num.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2, }); console.log(roundTo(5.015)); //returns 5.02 console.log(roundTo(1.555)); //returns 1.56

Rounding

Rounding means making a number simpler but keeping its value close to what it was. There is not a universal solution for everyone. There are several different rounding algorithms , your implementation can be different, depends on your requirements.

Rounding Numbers in JavaScript

In most cases JavaScript developers using Math.round() or toFixed() for rounded to the nearest integer. But, it seems like Math.round() is a better solution, but it is not! In some cases it will NOT round correctly. Also, toFixed() will also NOT round correctly in some cases.

Math.round()

var num = 5.015 console.log( Math.round((num+ Number.EPSILON)* 100)/100);
Output:
5.01 //wrong (should be 5.02)
In the above case the output is 5.01 instead of 5.02. If you execute the 5.015 with the above function roundTo() the output will be 5.02, that is the correct answer.

toFixed()

var num = 1.555 console.log( parseFloat(num).toFixed(2));
Output:
1.55 //wrong (should be 1.56)
In the above case the output is 1.55 instead of 1.56 . If you execute the 1.555 with the above function roundTo() the output will be 1.56, that is the correct answer.
Round to 2 decimal places in JavaScript
When the rounded number is increased, then the given number is said to be rounded up, whereas, if the rounded number is decreased, then it is said to be rounded down.