JavaScript round float to n decimal points

The best you can do with built in JavaScript functions is to round a number to the nearest integer using the method Math.round(x), so to round a float to n decimal points we need to come up with our own function.

The function round_float() rounds a floating point number x to n decimals, if you ommit the parameter n, the function will have the same behaviour as the round() method, here is the round_float function definition:

function round_float(x,n){
  if(!parseInt(n))
  	var n=0;
  if(!parseFloat(x))
  	return false;
  return Math.round(x*Math.pow(10,n))/Math.pow(10,n);
}
If you enjoyed this post, make sure you subscribe to my RSS feed!

Leave a Reply