Last active
December 15, 2015 20:29
-
-
Save edgardmessias/5319308 to your computer and use it in GitHub Desktop.
Rounding numbers with decimals.
For Round, Floor and Ceil.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example Number: 155.02
ceilNumber(155.02, 2) --> 155.02
Math.ceil(155.02 * Math.pow(10, 2)) / Math.pow(10, 2) --> 155.03