I’m trying to insert an NSNumber as a float value, into an NSArray, containing the floatValue from another NSNumber. I’m able to create the array fine, but when I access the object, it appears to only be an integer? I would expect that [NSNumber numberWithFloat:n] would generate a normal NSNumber with a float value..
int myInteger = 3;
NSNumber *myNum = [NSNumber numberWithInt:myInteger];
NSArray *arr = [NSArray arrayWithObjects:[NSNumber numberWithFloat:[myNum floatValue]], nil];
NSLog(@"%@", [arr objectAtIndex:0]);
Output:
2012-01-09 16:39:32.664 ObjectiveCSandbox[2961:707] 3
Additionally, I am able to use the %i pointer fine, and when I try and use the %f pointer in NSLog, the app crashes completely. What is going on here? This question is more academic than anything.
The default print behavior for
NSNumberwill trim off any leading zeros. So even if the underlying value is a float, if there’s no actual non-zero floating-point numbers, it’ll print like its an integer.As for your second question, using both
%iand%fis incorrect in your log statement, since you’re logging an object. You could use%pto log the pointer value of the object, if you wanted, but I don’t think that’s useful to you at the moment. If you want to use%fto get printf’s default float-printing behavior then you need to actually pass it a float instead of an object, as inNSLog(@"%f", [[arr objectAtIndex:0] floatValue]).If all you’re really interested in is whether the
NSNumberis storing a float internally, then you can print out the results of the-objcTypemethod, which will give you the@encode-string for the underlying value, but I’m not sure why you care what particular underlying formatNSNumberuses to store your value, as long as it can return you the value in your desired format (e.g. by calling-floatValue).