Round numbers in JavaScript with precision

JavaScript has an inbuilt Math object with several useful methods that you can use to perform common mathematical operations on numbers.
One of the most common tasks encountered when dealing with numbers in application development is rounding them off.
For this the Math.round() method comes in handy and can be used like this:


var someNumber=5.568942354894534;
var x=Math.round(someNumber); 

After the line is executed, x now holds the value 6.
But what if that is not we wanted? What if I wanted to round off the number to 2 places of decimals?

Unfortunately Math.round() does not provide rounding with precision.
But fortunately there is a simple solution for it.
Suppose I wanted the long floating value to be rounded to 2 places of decimal, here is what I am going to do:

  1. Move the decimal to 2 places right (multiply by 100)
  2. Call Math.round()
  3. Move decimal to 2 places left (divide by 100)

Here it is in JavaScript code:


var x=sumNumber*100;
x=Math.round(x);
x=x/100;

//or more compactly :

var x= Math.round(someNumber*100)/100;

x is now 5.69, just what we wanted!

Round function with precision

Now we are going to write our own round function based on the above technique that takes an extra precision parameter and returns a number rounded to precision decimal places.
Here it is:


function rnd(x,p) {
var a=[1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000,10000000000];
return Math.round(x*a[p])/a[p];
}

// Usage:
var x=rnd(someNumber,2);

This function supports rounding from 0 places of decimal to 10 places.
We could have calculated the multiplier for p precision using Math.pow(10,p) but this method is faster and usually you wouldn’t require rounding to more than 10 decimal places!
What if you accidentally passed a negative value or more than 10 as the second parameter p? In that case the function will return NaN since it will divide by undefined. To prevent that, we are going to add a couple of more lines of code


function rnd(x,p) {
//error checking
if(p<0) {
p=0;
} else if(p>10) {
p=10;
}
var a=[1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000,10000000000];
return Math.round(x*a[p])/a[p];
}

This will prevent any errors and return valid rounded decimals.
If you have a better solution for rounding numbers in JavaScript with precision, let us know in the comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

2018 All rights reserved | Powered by WordPress
Back to top
Theme by dynamicguru.com