Round a number to 2 decimal places in JavaScript
Question:
How to round a number to 2 decimal places in JavaScript? Answer:
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?"
Related snippets:
- Convert Fahrenheit to Celsius in JavaScript
- Convert kilometers to miles in JavaScript
- Convert Map values to array in JavaScript
- Round a number to 2 decimal places in JavaScript
- Convert string to int in JavaScript
- Convert snake case to camel case in JavaScript
- Capitalize words in a string using JavaScript
- Convert string to kebab case in JavaScript
- Convert string to character array in JavaScript
- Convert camel case to snake case in JavaScript
- Remove accents from a string in JavaScript
- Convert a string to sentence case in JavaScript
- Convert string to title case in JavaScript
- Convert string to snake case in JavaScript
- Convert string to pascal case in JavaScript
- Convert string to camel case in JavaScript
- Convert string to uppercase with JavaScript
- Convert a float number to integer in JavaScript
- Convert object to JSON string in JavaScript
- Parse JSON string in JavaScript
- convert number to string in JavaScript
Tags:
math, round, tofixed, epsilon, Technical term:
Round a number to 2 decimal places in JavaScript