views:

122

answers:

4

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

+5  A: 

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;
Aaronaught
this works ... plain and simple :)
mouthpiec
+4  A: 

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).

Alex Martelli
(n+8)/16 does not work. try, say 11. (11+8)/16 = 19/16. I think you're relying on dividing truncating here, so 19/16 = 1. but 11 should round to 16. So you still need to multiply by 16 to get the correct answer.
Wallacoloo
@wallacolo, you're right -- I forgot to multiply back -- editing to fix.
Alex Martelli
A: 

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;
tzaman
+1  A: 

Rounds the middle towards +∞

int RoundNearest16(int value)
{
    return (value + 8) & ~0xF;
}
280Z28