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