如何将 NSString 转换为 NSNumber

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.

转载于:https://stackoverflow.com/questions/1448804/how-to-convert-an-nsstring-into-an-nsnumber

18个回答

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.

weixin_41568184
叼花硬汉 But what if the string can contain either int or float?
接近 3 年之前 回复
csdnceshi80
胖鸭 Where did you find that it was currentLocale by default? I can confirm that numberFromString is using dot notation even on a French phone where comma is used. I can confirm that by default, when you output a number, it uses the current locale by default
大约 4 年之前 回复
csdnceshi78
程序go by default the locale is the +currentLocale, but you're correct; one must always consider the locale when dealing with converting stuff to-and-from human-readable form.
接近 7 年之前 回复
csdnceshi75
衫裤跑路 For people where it doesn't seem to work: Check if it's related to your locale. The NSNumberFormatter (as far as I know) by default uses the US locale, i.e. expects the decimal separator to be the "." character. If you use "," to separate the fraction, you may need to tell the formatter to use your current locale: [f setLocale:[NSLocale currentLocale]];
大约 7 年之前 回复
csdnceshi79
python小菜 +1 for 42, it's always good to see that!
7 年多之前 回复

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
csdnceshi74
7*4 In my use case, I needed to get an NSNumber dictionary key from an NSString, so @([@"42" intValue]) worked perfectly. Not worried about Locale.
大约 2 年之前 回复
csdnceshi55
~Onlooker This is the nicest solution on here, however I have just run a test and you will lose unsigned precision so WATCH OUT!!!
4 年多之前 回复
csdnceshi80
胖鸭 I agree, but do note that some other countries use the , and . the other way around (eg 42.000,42. Something floatValue probably does not account for?
接近 5 年之前 回复
csdnceshi62
csdnceshi62 this literal syntax didn't exist when this question was asked. I'd say this is the correct answer nowadays though.
大约 5 年之前 回复
csdnceshi65
larry*wei I prefer this based on profiling when I was parsing a large amount of string values. Using this syntax rather then an NSNumberFormatter led to significant reduction in time spent parsing the string to NSNumber. And yes the NSNumberFormatter was cached and reused.
5 年多之前 回复

You can use -[NSString integerValue], -[NSString floatValue], etc. However, the correct (locale-sensitive, etc.) way to do this is to use -[NSNumberFormatter numberFromString:] which will give you an NSNumber converted from the appropriate locale and given the settings of the NSNumberFormatter (including whether it will allow floating point values).

csdnceshi75
衫裤跑路 What @Thilo said. "Correct" and "locale-sensitive" are not synonyms. The correct thing to do actually depends upon how the number got into the string in the first place. If you read it from user input, then local-sensitive is what you want. From any other source (i.e. you put it there programmatically, you're consuming it as part of the response from some external API, etc.) local-sensitive is not appropriate and could even give incorrect results.
3 年多之前 回复
weixin_41568208
北城已荒凉 this does not work with ARC: it won't convert NSInteger to NSNumber. I have to further use [NSNumber numberWithInteger ...]
大约 5 年之前 回复
csdnceshi60
℡Wang Yan There are also huge performance differences among these methods.
6 年多之前 回复
csdnceshi65
larry*wei I had to convert @"2000" to an int and [@"2000" integerValue] worked nicely and is a little simpler for my case.
7 年多之前 回复
weixin_41568131
10.24 +q Depending on the situation, non-locale-sensitive might actually be the correct way.
大约 8 年之前 回复

You can also do this:

NSNumber *number = @([dictionary[@"id"] intValue]]);

Have fun!

you can also do like this code 8.3.3 ios 10.3 support

[NSNumber numberWithInt:[@"put your string here" intValue]]
NSDecimalNumber *myNumber = [NSDecimalNumber decimalNumberWithString:@"123.45"];
NSLog(@"My Number : %@",myNumber);

If you know that you receive integers, you could use:

NSString* val = @"12";
[NSNumber numberWithInt:[val intValue]];

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];
csdnceshi63
elliott.david This doesn't convert the NSInteger to a NSNumber. It converts it to a double.
4 年多之前 回复

Thanks All! I am combined feedback and finally manage to convert from text input ( string ) to Integer. Plus it could tell me whether the input is integer :)

NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [f numberFromString:thresholdInput.text];

int minThreshold = [myNumber intValue]; 

NSLog(@"Setting for minThreshold %i", minThreshold);

if ((int)minThreshold < 1 )
{
    NSLog(@"Not a number");
}
else
{
    NSLog(@"Setting for integer minThreshold %i", minThreshold);
}
[f release];

What about C's standard atoi?

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

Do you think there are any caveats?

共18条数据 1 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!