Javascript method to round decimal values


/ Published in: JavaScript
Save to your folder(s)

call the method like so: onkeypress="return inputLimiter(event, 'Numbers', this.value, 5);"


Copy this code and paste it in your HTML
  1. function roundNumber(number, decimal_points) {
  2. if (!decimal_points) return Math.round(number);
  3. if (number == 0) {
  4. var decimals = "";
  5. for (var i = 0; i < decimal_points; i++) decimals += "0";
  6. return "0." + decimals;
  7. }
  8.  
  9. var exponent = Math.pow(10, decimal_points);
  10. var num = Math.round((number * exponent)).toString();
  11. return num.slice(0, -1 * decimal_points) + "." + num.slice(-1 * decimal_points)
  12. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.