Question

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?

Était-ce utile?

La solution

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.

Autres conseils

This is how you do it:

unsigned long long number = [[jsonArray objectForKey:@"next"] longLongValue];
    NSNumber * numberValue = [NSNumber numberWithUnsignedLongLong:number];
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top