Divide int's and round up in Objective-C
I have 2 int's. How do I divide one by the other and then round up afterwards?
Solution 1:
If your ints are A
and B
and you want to have ceil(A/B) just calculate (A+B-1)/B
.
Solution 2:
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:
-(NSInteger)divideAndRoundUp:(NSInteger)a with:(NSInteger)b
{
if( a % b != 0 )
{
return a / b + 1;
}
return a / b;
}
Solution 4:
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