Round number up to the nearest multiple of 3

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


Solution 1:

    if(n > 0)
        return Math.ceil(n/3.0) * 3;
    else if( n < 0)
        return Math.floor(n/3.0) * 3;
    else
        return 3;

Solution 2:

Simply:

3.0*Math.ceil(n/3.0)

?

Solution 3:

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

Solution 4:

I'm answering this in psuedocode since I program mainly in SystemVerilog and Vera (ASIC HDL). % represents a modulus function.

round_number_up_to_nearest_divisor = number + ((divisor - (number % divisor)) % divisor)

This works in any case.

The modulus of the number calculates the remainder, subtracting that from the divisor results in the number required to get to the next divisor multiple, then the "magic" occurs. You would think that it's good enough to have the single modulus function, but in the case where the number is an exact multiple of the divisor, it calculates an extra multiple. ie, 24 would return 27. The additional modulus protects against this by making the addition 0.

Solution 5:

As mentioned in a comment to the accepted answer, you can just use this:

Math.ceil(x/3)*3

(Even though it does not return 3 when x is 0, because that was likely a mistake by the OP.)

Out of the nine answers posted before this one (that have not been deleted or that do not have such a low score that they are not visible to all users), only the ones by Dean Nicholson (excepting the issue with loss of significance) and beauburrier are correct. The accepted answer gives the wrong result for negative numbers and it adds an exception for 0 to account for what was likely a mistake by the OP. Two other answers round a number to the nearest multiple instead of always rounding up, one more gives the wrong result for negative numbers, and three more even give the wrong result for positive numbers.