Skip to content

Instantly share code, notes, and snippets.

@samhernandez
Created May 30, 2013 16:59
Show Gist options
  • Save samhernandez/5679434 to your computer and use it in GitHub Desktop.
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.)
/**
* 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;
}
@iomeone
Copy link

iomeone commented Oct 30, 2019

when you input roundToNearest(86, 10); the result should be 90.
so the function should be
Math.round((value + interval/2)/interval) * interval;

@rileysparsons
Copy link

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