Question

I'm trying to get the integer value of an NSNumber initialized with a float and I was expecting that intValue handle the conversion (as the docs say).

#import <Foundation/Foundation.h>
#import "Fraction.h"
#import "Complex.h"
#import "ComplexMathOps.h"

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];


    NSNumber    *myNum, *floatNum, *intNum;

    intNum = [NSNumber numberWithInt:100];
    floatNum = [NSNumber numberWithFloat:99];

    myNum = [floatNum intValue];

    NSLog(@"%@",myNum);



    [pool drain];
    return 0;
}

What am I doing wrong? What's the correct way to convert between different numeric types?

Was it helpful?

Solution

it works fine for me declaring it like this:

NSNumber * floatNum = [NSNumber numberWithFloat:99];
NSLog(@"%d",[floatNum intValue]);

OTHER TIPS

[floatNum intValue] returns an int-type, but you declared myNum as NSNumber. Declare myNum as int and everything works as expected.

What you should be doing is

myNum = [floatNum integerValue];

because integerValue returns an NSSNumber *

whereas intValue returns an int

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top