简体   繁体   中英

NSString to NSNumber convert

I try to convert a string :

3033547640189791162

with this method :

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

and this :

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

and both of them give me this number :

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

insted of :

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

Edit

When i try to use :

NSString *tmpId = @""3033547640189791162";

long i = [tmpId longLongValue];

i is equal to = -1631802438

int i = [tmpId intValue];

i is equal to = 2147483647

so i lose the original number value

If you want your NSNumber to hold an integer value you have to use [NSNumber numberWithInt:] :

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

You should also consider to make sure, that your NSString contains a valid integer value:

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

But there's a catch:

NSScanner validates the number inside the string as an integer, even though it should not … All ARM processors are 32-bit only, so the maximum range of an unsigned int is 0 to 4294967295 .

So using NSNumberFormatter is the safest way to get the right value, because it handles finding the right data type for you:

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

Moving my comment to answer:

Try NSNumber * myNumber = [NSNumber numberWithLongLong:[tmpId longLongValue]];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM