swiftobjective-cnsdecimalnumber

How to convert NSDecimalNumber to NSNumber


How to convert NSDecimalNumber To NSNumber? I have a NSDecimalNumber created inside a method which have to return a NSNumber object which can be checked later with [ ... isKindOfClass:[NSNumber class]]

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    id rn = [self haveToBeNSNumber];
    
    if ([rn isKindOfClass:[NSNumber class]]) {
        NSLog(@"It's NSNumber class object");
    }
    
    return YES;
}

- (NSNumber *)haveToBeNSNumber {
    
    NSDecimalNumber *dNumber = [NSDecimalNumber decimalNumberWithString:@"123.22"];
    
    return dNumber;
}

Solution

  • What is wrong with what you have?

    As @dan states NSDecimalNumber is a NSNumber, that is a NSDecimalNumber responds to all the methods of a NSNumber.

    You can cast the return type if you need to:

    return (NSNumber *)dNumber;
    

    Re rounding and accuracy: NSDecimalNumber in an exact decimal representation of the value, NSNumber is a close binary representation of the value, most decimal numbers that are not integers can not be represented with complete accuracy in binary (base 2).

    You control the displayed format with NSNumberFormatter. NSLog used the description method for display and formats the number the Apple developer liked.