Hi,
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
Hi,
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
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)) * factor;
16*((n+8)/16)
is the formula you want if, in particular, you want to convert 8 to 16 (it's equally close to 0 as to 16, so it's impossible to decide how to convert it based exclusively on the "nearest multiple" concept, you have to decide!-), and of course consistently 24 to 32, 40 to 48, and so forth. Use +7
in lieu of +8
if you'd rather convert 8 to 0 rather than to 16 (and consistently 24 to 16, and so forth).
To use a generic X
in lieu of the hardcoded 16
, then the formula is X*((n+X/2)/X)
(with the same proviso as in the above paragraph if X
is even).
Edit: no need to mess around with floating point numbers as other answers suggest, but you do need to multiply back by X
(which I had erroneously omitted).
You don't need to do any floating point division, it's unnecessary. Use the remainder operator:
int rem = value % multiple;
int result = value - rem;
if (rem > (multiple / 2))
result += multiple;
Rounds the middle towards +∞
int RoundNearest16(int value)
{
return (value + 8) & ~0xF;
}