views:

69

answers:

4

Hello,

is there a simple way to round the result of a division to upper integer ?

I would like to have this :

18/20 -> 1
19/20 -> 1
20/20 -> 1
21/20 -> 2
22/20 -> 2
23/20 -> 2

... and so on ...

38/20 -> 2
39/20 -> 2
40/20 -> 2
41/20 -> 3
42/20 -> 3
43/20 -> 3

Must I manager with NSNumberFormatter stuff ?

I didn't success to get an integer value with that and have an integer comparison to do.

Thanks in advance !

+1  A: 

You use the standard ceil() and ceilf() functions available i math.h

Claus Broch
A: 

Standard C supports double ceil(double x) and long double ceill(long double x). Perhaps the iPhone has these available? If your data is in integers in the first place, then you'll either have to find a clever trick or convert your ints to doubles first.

sarnold
+1  A: 
int x, y;
int result = (x + (y-1)) / y;

testing:

    int n = 20;
    for (int i = 1; i <= 50; i++) {         
        NSLog(@"%d+(%d-1) / %d = %d", i, n, n, (i+(n-1))/n);
    }
ohho
This is working like a charm !
Dough
A: 

NSNumberFormatter is used when converting between numbers and strings. In addition to the c functions on primitives mentioned already, you can use NSDecimalNumber and NSDecimalNumberHandler to perform the calculation and rounding given instances of NSNumber. When in doubt, refer to the documentation. Number and Value Programming Guide

Sample code to divide, round up to the next integer and display the result.

NSDecimalNumber *denominator = [NSDecimalNumber decimalNumberWithDecimal:[[NSNumber numberWithInteger:20] decimalValue]];

NSDecimalNumberHandler *numberHandler = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundUp scale:0 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:YES];

for (NSInteger counter = 1; counter <= 50; counter++) {

    NSDecimalNumber *numerator = [NSDecimalNumber decimalNumberWithDecimal:[[NSNumber numberWithInteger:counter] decimalValue]];

    NSDecimalNumber *result = [[numerator decimalNumberByDividingBy:denominator withBehavior:numberHandler] retain];

    NSLog(@"%@/%@ -> %d", numerator, denominator, [result integerValue]);

    [result release];
}
falconcreek