Skip to content

Instantly share code, notes, and snippets.

@aslakhellesoy
Created August 9, 2011 16:18
Show Gist options
  • Save aslakhellesoy/1134482 to your computer and use it in GitHub Desktop.
Save aslakhellesoy/1134482 to your computer and use it in GitHub Desktop.
Rounding up and down to nearest multiple
/** round n down to nearest multiple of m */
long roundDown(long n, long m) {
return n >= 0 ? (n / m) * m : ((n - m + 1) / m) * m;
}
/** round n up to nearest multiple of m */
long roundUp(long n, long m) {
return n >= 0 ? ((n + m - 1) / m) * m : (n / m) * m;
}
@aslakhellesoy
Copy link
Author

@paulca yes, very elegant. I love small snippets like that. Thanks for sharing!

@eoftedal
Copy link

eoftedal commented Aug 9, 2011

It seems roundUp is the inverse of roundDown so roundUp could be:
-1 * roundDown(-n, m)
Not sure that makes things clearer though

@aslakhellesoy
Copy link
Author

Who cares about clarity for this kind of code! It's just compact math :-) I'll do that refactoring tomorrow. Well spotted!

@jpillora
Copy link

jpillora commented Oct 7, 2012

👍

@diogoko
Copy link

diogoko commented May 24, 2018

Note that this code only works if all values are integer/long (using float/double gives wrong results in some cases).

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