How to convert an NSString into an NSNumber

How can I convert a NSString containing a number of any primitive data type (eg 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.


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.


你可以使用-[NSString integerValue]-[NSString floatValue]等。但是,正确的(区域设置敏感的等)的方式是使用-[NSNumberFormatter numberFromString:] ,它会给你一个NSNumber转换适当的语言环境并给定NSNumberFormatter的设置(包括是否允许浮点值)。


Objective-C

(Note: this method doesn't play nice with difference locales, but is slightly faster than a NSNumberFormatter )

NSNumber *num1 = @([@"42" intValue]);
NSNumber *num2 = @([@"42.42" floatValue]);

Swift

Simple but dirty way

// Swift 1.2
if let intValue = "42".toInt() {
    let number1 = NSNumber(integer:intValue)
}

// Swift 2.0
let number2 = Int("42')

// Swift 3.0
NSDecimalNumber(string: "42.42") 

// Using NSNumber
let number3 = NSNumber(float:("42.42" as NSString).floatValue)

The extension-way This is better, really, because it'll play nicely with locales and decimals.

extension String {

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

Now you can simply do:

let someFloat = "42.42".numberValue
let someInt = "42".numberValue
链接地址: http://www.djcxy.com/p/30664.html

上一篇: 是否可以在iOS模拟器中禁用网络?

下一篇: 如何将NSString转换为NSNumber