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];
}