如何将NSString转换为NSNumber [英] How to convert an NSString into an NSNumber
问题描述
如何转换包含许多原始数据类型(例如int
,float
,char
,unsigned int
等)的NSString
?问题是,我不知道字符串在运行时将包含哪种数字类型.
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];
感谢您的帮助.
推荐答案
使用NSNumberFormatter
:
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterDecimalStyle;
NSNumber *myNumber = [f numberFromString:@"42"];
如果字符串不是有效数字,则myNumber
将为nil
.如果它是一个有效的数字,那么您现在具有NSNumber
的全部优点,可以弄清它实际上是哪种数字.
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转换为NSNumber的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!