Languages
[Edit]
EN

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

11 points
Created by:
Root-ssh
6442

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
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists 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.