Divide int and round in Objective-C

I have 2 int. How to divide one into another, and then round off later?

+66
objective-c
Feb 07 '11 at 20:53
source share
5 answers

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

+196
Feb 07 2018-11-11T00:
source share

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 
+33
Jun 13 '12 at 13:19
source share
 -(NSInteger)divideAndRoundUp:(NSInteger)a with:(NSInteger)b { if( a % b != 0 ) { return a / b + 1; } return a / b; } 
+3
Feb 07 2018-11-11T00:
source share

As in C, you can use both float methods 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 
+3
Feb 07 2018-11-11T00:
source share

If you are looking for 2.1 roundup> 3

 double row = _datas.count / 3; double rounded = ceil(_datas.count / 3); if(row > rounded){ row += 1; }else{ } 
0
Nov 29 '17 at 11:20
source share



All Articles