Returning the nearest multiple value of a number
c#
Solution
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?!
Problem
I need a function by which I will be able to convert a number to a nearest value of a given multiple. Eg i want an array of number to be set to the neareast multiple of 16, so 2 = 0, 5 = 0, 11 = 16, 17 = 16, 30 = 32 etc thanks