Languages
[Edit]
EN

JavaScript - round with precision using arrow function in ES6

6 points
Created by:
JustMike
3593

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
Hey 👋
Would you like to know what we do?
  • Dirask is online IT community for professionals and hobbyist to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.