How can I convert a NSString
containing a number of any primitive data type (e.g. int
, float
, char
, unsigned int
, etc.)? The problem is, I don't know which number type the string will contain at runtime.
I have an idea how to do it, but I'm not sure if this works with any type, also unsigned and floating point values:
long long scannedNumber;
NSScanner *scanner = [NSScanner scannerWithString:aString];
[scanner scanLongLong:&scannedNumber];
NSNumber *number = [NSNumber numberWithLongLong: scannedNumber];
Thanks for the help.
I wanted to convert a string to a double. This above answer didn't quite work for me. But this did: How to do string conversions in Objective-C?
All I pretty much did was:
I know this is very late but below code is working for me.
Try this code
NSNumber *number = @([dictionary[@"keyValue"] intValue]]);
This may help you. Thanks
you can also do like this code 8.3.3 ios 10.3 support
What about C's standard
atoi
?Do you think there are any caveats?
Use an
NSNumberFormatter
:If the string is not a valid number, then
myNumber
will benil
. If it is a valid number, then you now have all of theNSNumber
goodness to figure out what kind of number it actually is.