Divide int's and round up in Objective-C

Objective C

Objective C Problem Overview


I have 2 int's. How do I divide one by the other and then round up afterwards?

Objective C Solutions


Solution 1 - Objective C

If your ints are A and B and you want to have ceil(A/B) just calculate (A+B-1)/B.

Solution 2 - Objective C

What about:

float A,B; // this variables have to be floats!
int result = floor(A/B); // rounded down
int result = ceil(A/B); // rounded up

Solution 3 - Objective C

-(NSInteger)divideAndRoundUp:(NSInteger)a with:(NSInteger)b
{
  if( a % b != 0 )
  {
    return a / b + 1;
  }
  return a / b;
}

Solution 4 - Objective C

As in C, you can cast both to float and then round the result using a rounding function that takes a float as input.

int a = 1;
int b = 2;

float result = (float)a / (float)b;

int rounded = (int)(result+0.5f);
i

Solution 5 - Objective C

If you looking for 2.1 roundup> 3

double row = _datas.count / 3;
double rounded = ceil(_datas.count / 3);
if(row > rounded){
    row += 1;
}else{
    
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSleeView Question on Stackoverflow
Solution 1 - Objective CHowardView Answer on Stackoverflow
Solution 2 - Objective Ckraag22View Answer on Stackoverflow
Solution 3 - Objective CThomson ComerView Answer on Stackoverflow
Solution 4 - Objective CNathan GarabedianView Answer on Stackoverflow
Solution 5 - Objective CMuhammad AsyrafView Answer on Stackoverflow