Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community of people that helps each other.

If you think you have some skills to help others

help someone and become a part of our community - List Q & A

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

0 contributions
11 points

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
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more