问题
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.
回答1:
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
回答2:
42.00000
is not a string mate, why not @"42.00000"
?
来源:https://stackoverflow.com/questions/22413605/nsnumberformatter-numberfromstring-decimal-number