EN
JavaScript - round with precision using arrow function in ES6
6
points
In this short article, we would like to show how to write arrow function that rounds numbers with precision up to n
decimal places in modern JavaScript (>= ES6)
// ONLINE-RUNNER:browser;
const round = (value, precision) => {
const power = Math.pow(10, precision);
return Math.round(value * power) / power;
};
// Usage example:
console.log( round( 5 , 0 ) ); // 5
console.log( round( 5. , 0 ) ); // 5
console.log( round( .5, 0 ) ); // 1
console.log( round( 1.2345, 0 ) ); // 1
console.log( round( 1.2345, 1 ) ); // 1.2
console.log( round( 1.2345, 2 ) ); // 1.23
console.log( round( 1.2345, 3 ) ); // 1.235
console.log( round( -1.2345, 0 ) ); // -1
console.log( round( -1.2345, 1 ) ); // -1.2
console.log( round( -1.2345, 2 ) ); // -1.23
console.log( round( -1.2345, 3 ) ); // -1.234
console.log( round( 12345, -1 ) ); // 12350
console.log( round( 12345, -2 ) ); // 12300
console.log( round( 12345, -3 ) ); // 12000