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.
xxxxxxxxxx
1
function roundPrecised(number, precision) {
2
var power = Math.pow(10, precision);
3
4
return Math.round(number * power) / power;
5
}
6
7
8
// Usage example:
9
10
console.log( roundPrecised( 5 , 0 ) ); // 5
11
console.log( roundPrecised( 5. , 0 ) ); // 5
12
console.log( roundPrecised( .5, 0 ) ); // 1
13
14
console.log( roundPrecised( 1.2345, 0 ) ); // 1
15
console.log( roundPrecised( 1.2345, 1 ) ); // 1.2
16
console.log( roundPrecised( 1.2345, 2 ) ); // 1.23
17
console.log( roundPrecised( 1.2345, 3 ) ); // 1.235
18
19
console.log( roundPrecised( -1.2345, 0 ) ); // -1
20
console.log( roundPrecised( -1.2345, 1 ) ); // -1.2
21
console.log( roundPrecised( -1.2345, 2 ) ); // -1.23
22
console.log( roundPrecised( -1.2345, 3 ) ); // -1.234
23
24
console.log( roundPrecised( 12345, -1 ) ); // 12350
25
console.log( roundPrecised( 12345, -2 ) ); // 12300
26
console.log( roundPrecised( 12345, -3 ) ); // 12000