Skip to content

Instantly share code, notes, and snippets.

@mikesprague
Created June 6, 2013 12:41
Show Gist options
  • Save mikesprague/5721210 to your computer and use it in GitHub Desktop.
Save mikesprague/5721210 to your computer and use it in GitHub Desktop.
JavaScript: Math.round (modified to round number with decimal places)
Math.round = (function() {
var originalRound = Math.round;
return function(number, precision) {
precision = Math.abs(parseInt(precision)) || 0;
var multiplier = Math.pow(10, precision);
return (originalRound(number * multiplier) / multiplier);
};
})();
/*
example usage:
Math.round(1.2345, 2) // returns 1.23
Math.round(4.789, 1) // returns 4.8
above modification can be applied to Math.ceil and Math.floor as well
borrowed from: http://www.anujgakhar.com/2013/06/06/rounding-numbers-with-decimal-places-in-javascript/
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment