EN
JavaScript - round with precision to n decimal places
11
points
In this article, we would like to show you how to round numbers with precision to n
decimal places in JavaScript.
1. Custom round method examples
// ONLINE-RUNNER:browser;
function roundPrecised(number, precision) {
var power = Math.pow(10, precision);
return Math.round(number * power) / power;
}
// Usage example:
console.log( roundPrecised( 5 , 0 ) ); // 5
console.log( roundPrecised( 5. , 0 ) ); // 5
console.log( roundPrecised( .5, 0 ) ); // 1
console.log( roundPrecised( 1.2345, 0 ) ); // 1
console.log( roundPrecised( 1.2345, 1 ) ); // 1.2
console.log( roundPrecised( 1.2345, 2 ) ); // 1.23
console.log( roundPrecised( 1.2345, 3 ) ); // 1.235
console.log( roundPrecised( -1.2345, 0 ) ); // -1
console.log( roundPrecised( -1.2345, 1 ) ); // -1.2
console.log( roundPrecised( -1.2345, 2 ) ); // -1.23
console.log( roundPrecised( -1.2345, 3 ) ); // -1.234
console.log( roundPrecised( 12345, -1 ) ); // 12350
console.log( roundPrecised( 12345, -2 ) ); // 12300
console.log( roundPrecised( 12345, -3 ) ); // 12000