4

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.

user3250560
  • 646
  • 2
  • 9
  • 15
  • 1
    Parsing `42.00000` will only work if the device's (or simulator's) locale is set to a locale that uses the period for the decimal separator. – rmaddy Mar 14 '14 at 19:06

2 Answers2

15

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

Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Thx, that works, what is the difference between en_US_POSIX and en_US? – user3250560 Mar 14 '14 at 19:26
  • @user3250560: I don't know the formal definition, but in https://developer.apple.com/library/ios/qa/qa1480/_index.html (which is about *dates*, where similar locale dependent problems occur), it is described as *... "en_US_POSIX", a locale that's specifically designed to yield US English results regardless of both user and system preferences. "en_US_POSIX" is also invariant in time (if the US, at some point in the future, changes the way it formats dates, "en_US" will change to reflect the new behaviour, but "en_US_POSIX" will not), and between machines ...* – Martin R Mar 14 '14 at 19:30
1

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

Neeku
  • 3,646
  • 8
  • 33
  • 43
gran33
  • 12,421
  • 9
  • 48
  • 76