Languages
[Edit]
EN

JavaScript - round with precision to n decimal places

11 points
Created by:
Root-ssh
177980

In this article, we would like to show you how to round numbers with precision to n decimal places in JavaScript.

1. Custom round method examples

// ONLINE-RUNNER:browser;

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

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


// Usage 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

Alternative titles

  1. JavaScript - how to round with precision to n decimal places?
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