Javascript – Round numbers to some decimal places


Javascript’s Math.round function allows a user to round a float to an integer. But most of the time we need some function that’ll let us round the number to any decimal places we want. So here is the function that’ll solve your problem:

function roundNumber(num,decimal){
     var numerator = Math.round(num * Math.pow(10, decimal));
     var denominator = Math.pow(10, decimal);
     return  numerator / denominator;
}

num is the number you want to round.
decimal is the number of decimal places.


Try it here
Enter the number you want to round up:

Enter the number of decimal places:

Here is the result:

,

  1. No comments yet.
(will not be published)