NSString转换为NSNumber

时间:2012-03-11 10:12:02

标签: iphone objective-c

我尝试转换字符串:

3033547640189791162

用这种方法:

NSNumber * myNumber = [NSNumber numberWithDouble:[tmpId doubleValue]];

和此:

NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterNoStyle];
NSNumber * myNumber = [f numberFromString:tmpId];
[f release];

他们俩都给了我这个号码:

<CFNumber 0x13a2b0 [0x3f54c9f8]>{value = +3033547640189791232.00000000000000000000, type = kCFNumberFloat64Type}

绝对:

<CFNumber 0x1b5550 [0x3f54c9f8]>{value = +3033547640189791232, type = kCFNumberSInt64Type}

修改

当我尝试使用时:

NSString *tmpId = @""3033547640189791162";

long i = [tmpId longLongValue];

我等于= -1631802438

int i = [tmpId intValue];

我等于= 2147483647

所以我丢失了原始数字值

2 个答案:

答案 0 :(得分:5)

如果您希望NSNumber保持整数值,则必须使用[NSNumber numberWithInt:]

NSNumber *myNumber = [NSNumber numberWithInt:[tmpId intValue]];

您还应该考虑确保您的NSString包含有效的整数值:

NSScanner* scan = [NSScanner scannerWithString:tmpId]; 
int isInt; 
if ( [scan scanInt:&isInt] && isInt ) {
    NSLog(@"value is an integer: %i",isInt);
}

但是有一个问题:

NSScanner将字符串中的数字验证为整数,即使它不应该......所有ARM处理器都只是32位,因此unsigned int的最大范围是04294967295

因此,使用NSNumberFormatter是获得正确值的最安全方法,因为它可以为您找到正确的数据类型:

NSString *tmpId = @"3033547640189791162";
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *myNumber = [f numberFromString:tmpId];

答案 1 :(得分:1)

移动我的评论回答:

尝试NSNumber * myNumber = [NSNumber numberWithLongLong:[tmpId longLongValue]];