Returning the nearest multiple value of a number
Some division and rounding should be all you need for this:
int value = 30;
int factor = 16;
int nearestMultiple =
(int)Math.Round(
(value / (double)factor),
MidpointRounding.AwayFromZero
) * factor;
Be careful using this technique. The Math.Round(double)
overload believes the evil mutant MidpointRounding.ToEven
is the best default behavior, even though what we all learned before in school is what the CLR calls MidpointRounding.AwayFromZero
. For example:
var x = Math.Round(1.5); // x is 2.0, like you'd expect
x = Math.Round(0.5); // x is 0. WAT?!
You don't need to do any floating point division, it's unnecessary. Use the remainder operator:
int rem = val % multiple;
int result = val - rem;
if (rem >= (multiple / 2))
result += multiple;