How can I get NSDecimal to round to the nearest integer value?

593 views Asked by At

I am using NSDecimal because I have to store extremely large values for my application. I would like to be able to use the NSDecimalDivide function to divide two NSDecimals and round the result to the nearest integer.

    NSDecimal testOne = [[NSDecimalNumber decimalNumberWithString:@"1064"] decimalValue];
    NSDecimal cost = [[NSDecimalNumber    decimalNumberWithString:@"10"]decimalValue];
    NSDecimal value;
    NSDecimalDivide(&value, &testOne, &cost, NSRoundDown);
    NSString *string = NSDecimalString(&value, _usLocale);
    NSLog(@"Here is the cost%@",string);

This out puts 106.4 I would like it to output 106. Does anyone know how to round a NSDecimal number to the integer value?

2

There are 2 answers

0
Sulthan On BEST ANSWER

One possible way to do that is using a NSDecimalNumberHandler with scale set to 0.

NSDecimalNumber *number1 = [NSDecimalNumber decimalNumberWithString:@"1064"];
NSDecimalNumber *number2 = [NSDecimalNumber decimalNumberWithString:@"10"];

NSDecimalNumberHandler *behavior = [[NSDecimalNumberHandler alloc] initWithRoundingMode:NSRoundDown
                                                                                  scale:0
                                                                       raiseOnExactness:NO
                                                                        raiseOnOverflow:NO
                                                                       raiseOnUnderflow:NO
                                                                    raiseOnDivideByZero:YES];

NSDecimalNumber *result = [number1 decimalNumberByDividingBy:number2 withBehavior:behavior];

NSLog(@"Here is the cost %@", result);

Note that I am not using the primitive NSDecimal at all and you I would advise you the same.

However, if you want to work with NSDecimal directly, you can use the handy NSDecimalRound function.

0
matt On

Wrap the NSDecimal up as an NSDecimalNumber and use decimalNumberByRoundingAccordingToBehavior:. This lets you specify the exact rounding behavior you desire.