How to convert an NSString into an NSNumber

2018-12-31 18:19发布

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.

18条回答
裙下三千臣
2楼-- · 2018-12-31 18:40

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:

double myDouble = [myString doubleValue];
查看更多
心情的温度
3楼-- · 2018-12-31 18:41

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

查看更多
余生请多指教
4楼-- · 2018-12-31 18:42
extension String {

    var numberValue:NSNumber? {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        return formatter.number(from: self)
    }
}

let someFloat = "12.34".numberValue
查看更多
残风、尘缘若梦
5楼-- · 2018-12-31 18:43

you can also do like this code 8.3.3 ios 10.3 support

[NSNumber numberWithInt:[@"put your string here" intValue]]
查看更多
人气声优
6楼-- · 2018-12-31 18:44

What about C's standard atoi?

int num = atoi([scannedNumber cStringUsingEncoding:NSUTF8StringEncoding]);

Do you think there are any caveats?

查看更多
情到深处是孤独
7楼-- · 2018-12-31 18:45

Use an NSNumberFormatter:

NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterDecimalStyle;
NSNumber *myNumber = [f numberFromString:@"42"];

If the string is not a valid number, then myNumber will be nil. If it is a valid number, then you now have all of the NSNumber goodness to figure out what kind of number it actually is.

查看更多
登录 后发表回答