C++: Rounding up to the nearest multiple of a number

Robben_Ford_Fan_boy picture Robben_Ford_Fan_boy · Aug 4, 2010 · Viewed 133.8k times · Source

OK - I'm almost embarrassed posting this here (and I will delete if anyone votes to close) as it seems like a basic question.

Is this the correct way to round up to a multiple of a number in C++?

I know there are other questions related to this but I am specficially interested to know what is the best way to do this in C++:

int roundUp(int numToRound, int multiple)
{
 if(multiple == 0)
 {
  return numToRound;
 }

 int roundDown = ( (int) (numToRound) / multiple) * multiple;
 int roundUp = roundDown + multiple; 
 int roundCalc = roundUp;
 return (roundCalc);
}

Update: Sorry I probably didn't make intention clear. Here are some examples:

roundUp(7, 100)
//return 100

roundUp(117, 100)
//return 200

roundUp(477, 100)
//return 500

roundUp(1077, 100)
//return 1100

roundUp(52, 20)
//return 60

roundUp(74, 30)
//return 90

Answer

Mark Ransom picture Mark Ransom · Aug 4, 2010

This works for positive numbers, not sure about negative. It only uses integer math.

int roundUp(int numToRound, int multiple)
{
    if (multiple == 0)
        return numToRound;

    int remainder = numToRound % multiple;
    if (remainder == 0)
        return numToRound;

    return numToRound + multiple - remainder;
}

Edit: Here's a version that works with negative numbers, if by "up" you mean a result that's always >= the input.

int roundUp(int numToRound, int multiple)
{
    if (multiple == 0)
        return numToRound;

    int remainder = abs(numToRound) % multiple;
    if (remainder == 0)
        return numToRound;

    if (numToRound < 0)
        return -(abs(numToRound) - remainder);
    else
        return numToRound + multiple - remainder;
}