Created
May 30, 2013 16:59
-
-
Save samhernandez/5679434 to your computer and use it in GitHub Desktop.
Round a number to the nearest interval of a given number. (Because I always forget how darned simple this is.)
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
/** | |
* Returns the number rounded to the nearest interval. | |
* Example: | |
* | |
* roundToNearest(80, 100); // 100 | |
* roundToNearest(25, 15); // 30 | |
* | |
* @param {number} value The number to round | |
* @param {number} interval The numeric interval to round to | |
* @return {number} | |
*/ | |
function roundToNearest(value, interval) { | |
return Math.round(value/interval) * interval; | |
} |
when you input roundToNearest(86, 10); the result should be 90.
so the function should be
Math.round((value + interval/2)/interval) * interval;
No, this works as written. Your function incorrectly returns the following for inputs of 40
and 10
: 50
;
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
when you input roundToNearest(86, 10); the result should be 90.
so the function should be
Math.round((value + interval/2)/interval) * interval;