Languages
[Edit]
EN

JavaScript - round with precision using arrow function in ES6

6 points
Created by:
Wesley
501

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

// 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
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - math (popular problems)

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