Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert long NSString to NSNumber

I am unable to reliably convert longer NSString to NSNumber. Specifically, I am converting MPMediaEntityPropertyPersistentID as a string to a NSNumber Sometimes it works, usually it doesn't.

Conversion code:

 NSString *keke = [jsonArray objectForKey:@"next"];
 NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
 [f setNumberStyle:NSNumberFormatterDecimalStyle];
 NSNumber *persistentIDasNumber = [f numberFromString:keke];

Here is an example of a successful string to number conversion:

String: 3813955856659208324
Number: 3813955856659208324

And here is an unsuccessful conversion:

String: 12790162104953153719 
Number:1.279016210495315e+19

It's close but what is happening at the end? Is it too large?

like image 486
john cs Avatar asked Sep 01 '13 02:09

john cs


1 Answers

Apparently the largest integer number that can be processed with NSNumberFormatter is long long, which is 9223372036854775807. Anything beyond that will lose precision and not come out as you put it in.

Instead use NSDecimalNumber, a concrete subclass of NSNumber. And it can even parse strings itself:

NSDecimalNumber *dn=[[NSDecimalNumber alloc]initWithString:@"12790162104953153719"];
NSLog(@"dn: %@",dn);

NSDecimalNumber can handle up to 38 digit long decimal numbers before it loses precision.

like image 135
Gerd K Avatar answered Sep 28 '22 20:09

Gerd K