Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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;
}
@paulca

This comment has been minimized.

Copy link

@paulca paulca commented Aug 9, 2011

I needed to round up or down to the nearest n:

(i % n) > n/2) ? i + n - i%n : i - i%n
@aslakhellesoy

This comment has been minimized.

Copy link
Owner Author

@aslakhellesoy aslakhellesoy commented Aug 9, 2011

@paulca neat

@paulca

This comment has been minimized.

Copy link

@paulca paulca commented Aug 9, 2011

@aslakhellesoy — It's actually one of my favorite pieces of code from the last 5 years! Credit actually goes to @destraynor for the logic.

@aslakhellesoy

This comment has been minimized.

Copy link
Owner Author

@aslakhellesoy aslakhellesoy commented Aug 9, 2011

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

@eoftedal

This comment has been minimized.

Copy link

@eoftedal 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

This comment has been minimized.

Copy link
Owner Author

@aslakhellesoy aslakhellesoy commented Aug 9, 2011

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

@jpillora

This comment has been minimized.

Copy link

@jpillora jpillora commented Oct 7, 2012

👍

@diogoko

This comment has been minimized.

Copy link

@diogoko 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
You can’t perform that action at this time.