Created
August 9, 2011 16:18
-
-
Save aslakhellesoy/1134482 to your computer and use it in GitHub Desktop.
Rounding up and down to nearest multiple
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
/** 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; | |
} |
@paulca neat
@aslakhellesoy — It's actually one of my favorite pieces of code from the last 5 years! Credit actually goes to @destraynor for the logic.
@paulca yes, very elegant. I love small snippets like that. Thanks for sharing!
It seems roundUp is the inverse of roundDown so roundUp could be:
-1 * roundDown(-n, m)
Not sure that makes things clearer though
Who cares about clarity for this kind of code! It's just compact math :-) I'll do that refactoring tomorrow. Well spotted!
👍
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
I needed to round up or down to the nearest n: