Languages
[Edit]
EN

JavaScript - how to round with precision to n decimal places?

11 points
Created by:
Root-ssh
68810

In JavaScript it is possible to round to n decimal places in following way.

1. Custom round method examples

// ONLINE-RUNNER:browser;

function roundPrecised(number, precision) {
	var power = Math.pow(10, precision);

  	return Math.round(number * power) / power;
}

// Example:

console.log( roundPrecised(     5  ,  0 ) ); // 5
console.log( roundPrecised(     5. ,  0 ) ); // 5
console.log( roundPrecised(      .5,  0 ) ); // 1

console.log( roundPrecised(  1.2345,  0 ) ); // 1
console.log( roundPrecised(  1.2345,  1 ) ); // 1.2
console.log( roundPrecised(  1.2345,  2 ) ); // 1.23
console.log( roundPrecised(  1.2345,  3 ) ); // 1.235

console.log( roundPrecised( -1.2345,  0 ) ); // -1
console.log( roundPrecised( -1.2345,  1 ) ); // -1.2
console.log( roundPrecised( -1.2345,  2 ) ); // -1.23
console.log( roundPrecised( -1.2345,  3 ) ); // -1.234

console.log( roundPrecised(   12345, -1 ) ); // 12350
console.log( roundPrecised(   12345, -2 ) ); // 12300
console.log( roundPrecised(   12345, -3 ) ); // 12000

See also

  1. JavaScript - Math.round() method example
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join