Reputation: 7890
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}
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
Upvotes: 1
Views: 2615
Reputation: 17877
Moving my comment to answer:
Try NSNumber * myNumber = [NSNumber numberWithLongLong:[tmpId longLongValue]];
Upvotes: 1
Reputation: 11962
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];
Upvotes: 4