Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSNumberFormatter numberFromString decimal number

I'm trying to parse a NSString with a NSNumberFormatter like following.

NSNumberFormatter *myFormatter = [[[NSNumberFormatter alloc] init];
NSNumber *myNumber = [myFormatter numberFromString:@"42.00000"];

numberFromString returns a NSNumber object in the simulator but not on a device.

The decimals (.00000) are causing the return value to be nil on a device because parsing 42 (without the decimals) works just fine (both in the simulator and on a device).

The reason I'm using a NSNumberFormatter is because is like how it returns nil if the string is not a valid number (which is working against me here :p). NSString doubleValue does not provide this kind of behaviour. Also, NSDecimalNumber decimalNumberWithString doesn't do the job because [NSDecimalNumber decimalNumberWithString:@"4a2.00000"] returns 4.

Any ideas why this would not work on a device?

Is it the locale? I tried setting myFormatter.numberStyle = NSNumberFormatterNoStyle and NSNumberFormatterDecimalStyle but it changes nothing.

like image 567
user3250560 Avatar asked Dec 04 '22 07:12

user3250560


2 Answers

As @rmaddy already said in a comment, the decimal separator of NSNumberFormatter is locale dependent. If you have a fixed input format with the dot as decimal separator, you can set the "POSIX locale":

NSNumberFormatter *myFormatter = [[NSNumberFormatter alloc] init];
[myFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
NSNumber *myNumber = [myFormatter numberFromString:@"42.00000"];

Alternatively, you can use NSScanner to parse a double value, as e.g. described here: parsing NSString to Double

like image 121
Martin R Avatar answered Dec 30 '22 05:12

Martin R


42.00000 is not a string mate, why not @"42.00000"?

like image 23
gran33 Avatar answered Dec 30 '22 05:12

gran33