Introduction
In JavaScript, there are situations when we need to round to at most 2 decimal places. In this article, we'll look at how to do it.
How to correctly round to at most 2 decimal places in JavaScript
To correctly round to at most 2 decimal places in JavaScript we need to use Math.round()
function:
function roundTo(num, decimalPlaces = 0) {
num = Math.round(num + "e" + decimalPlaces);
return Number(num + "e" + -decimalPlaces);
}
console.log(roundTo(0.5)); // 1
console.log(roundTo(-0.5)); // 0
console.log(roundTo(1.005, 2)); // 1.01
console.log(roundTo(2.175, 2)); // 2.18
console.log(roundTo(5.015, 2)); // 5.02
console.log(roundTo(-1.005, 2)); // -1
console.log(roundTo(-2.175, 2)); // -2.17
console.log(roundTo(-5.015, 2)); // -5.01
Conclusion
In this article, we learned how to correctly round to at most 2 decimal places in JavaScript.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}