Skip to content

Instantly share code, notes, and snippets.

@edgardmessias
Last active December 15, 2015 20:29
Show Gist options
  • Save edgardmessias/5319308 to your computer and use it in GitHub Desktop.
Save edgardmessias/5319308 to your computer and use it in GitHub Desktop.
Rounding numbers with decimals. For Round, Floor and Ceil.
function roundNumber(num, dec) {
return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
}
function floorNumber(num, dec) {
return roundNumber(num - (5 / Math.pow(10, dec + 1)), dec);
}
function ceilNumber(num, dec) {
var numStr = num.toString();
var decCount = (numStr.split('.')[1] || []).length;
return roundNumber(num + (5 / Math.pow(10, dec + 1)) - (1 / Math.pow(10, dec + decCount)), dec);
}
@edgardmessias
Copy link
Author

Example Number: 155.02

ceilNumber(155.02, 2) --> 155.02

Math.ceil(155.02 * Math.pow(10, 2)) / Math.pow(10, 2) --> 155.03

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment