Languages
[Edit]
EN

JavaScript - round with precision using arrow function in ES6

6 points
Created by:
JustMike
28510

In this short article we would like to show how 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
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join