- Instant help with your JavaScript coding problems

# Round a number to 2 decimal places in JavaScript

Question:
How to round a number to 2 decimal places in JavaScript?
``````function roundTo2(num) {
return Math.round( ( num + Number.EPSILON ) * 100 ) / 100;
}

``````
Description:

Rounding a number in JavaScript can be tricky in some situations when using floating-point numbers. The problem is that floating-point numbers cannot represent all decimals precisely in binary. This can lead to unexpected results, such as `0.1 + 0.2 === 0.3` returning `false`

To eliminate this problem use the `Number.EPSILON` property, that represents the difference between 1 and the smallest floating-point number greater than 1.

Some tutorials propose to use the `toFixed` method, that formats the number and also rounds it if needed, but it also suffers from the edge cases.

Reference:
The round reference
Share "How to round a number to 2 decimal places in JavaScript?"
Tags:
math, round, tofixed, epsilon,
Technical term:
Round a number to 2 decimal places in JavaScript