views:

135

answers:

5

Hay, how would i go about rounded a number up the nearest multiple of 3?

ie

25 would return 27
1 would return 3
0 would return 3
6 would return 6

thanks

+8  A: 
    if(n > 0)
        return Math.ceil(n/3.0) * 3;
    else if( n < 0)
        return Math.floor(n/3.0) * 3;
    else
        return 3;
Cambium
dont think this would work, would only bring back the same number
RobertPitt
Why is that? Say we have 7 and we want 9, 7/3=2.33333, ceil(2.3333)=3, 3*3=9. Am I missing something?
Cambium
Cambium is right - it works, because it rounds the n/3 up to the nearest whole number before multiplying by 3 again.
Jake
@robertPitt, works just fine
Gaby
Doesn't work for the OPs requirement for n = 0.
Sani Huttunen
@RobertPitt: This works just as it should! you should try it before claiming it isn't correct.
jigfox
@Sani, indeed .. although it seems like a bogus requirement..
Gaby
@Sani, you are right
Cambium
@Gaby: I agree...
Sani Huttunen
@Sani Huttunen, that was my point, i was talking about the 0 issue, @Jens F, I did as this does not meet the OP's requirements :/ i know the math is right
RobertPitt
It does look like the requirement is wrong, but thats not necessarily for developers to decide. Give the customer what they want, and then charge them through the nose for the subsequent change ;)
Visage
@visage, *chuckle*
Gaby
@RobertPitt: thanks, you were right, I overlooked the requirements :)
Cambium
n would never be 0. So this works fine.
dotty
+1  A: 

(n - n mod 3)+3

Visage
javascript's mod operator is %, additionally it will (*mistakenly*) round up even numbers that are already multiple's of 3..
Gaby
I wasnt 100% sure what it was, so just wrote pseudocode....
Visage
That's how I wanted to post it. I think I'll never answer again on a math question. One little mistake and you get down votes immediately. Worse that in school ;) But hey, at least I was able to get the "peer pressure" badge :)
Kau-Boy
@visage, it will change 3 to 6 (*and any multiples of 3*)... it should not ..
Gaby
A: 

Here you are!

Number.prototype.roundTo = function(num) {
    var resto = this%num;
    if (resto <= (num/2)) { 
        return this-resto;
    } else {
        return this+num-resto;
    }
}

Examples:

y = 236.32;
x = y.roundTo(10);

// results in x = 240

y = 236.32;
x = y.roundTo(5);

// results in x = 235
Makram Saleh
A: 
if(x%3==0)
    return x
else
    return ((x/3|0)+1)*3
James
A: 
(((x - 1) / 3) + 1) * 3

no need to use floating point arithmetics.

Yossarian