Rounding a number to a specific precision in JavaScript
The function to use to round a number in JavaScript is called Math.round
.
console.log(Math.round(3.14));
// output: 3
The Math.round
function will always round to a whole number, and sometimes you want to round a number to a specific precision.
This is a tiny and handy function to round a number to a specific precision:
function round(value, precision = 0) {
const exponent = Math.pow(10, precision);
return Math.round(value * exponent) / exponent;
}
Less is more!