According to the documentation, [NSDecimalNumber decimalNumberWithString:]
should use the locale decimal separator:
Whether the NSDecimalSepa
NSDecimalNumber is simply a storage class for number-type data. It's running a parser (NSNumberFormatter) on the string you pass it to create its number. The reason your second log statement works "better" is because the first one is using the default number format locale (it looks like it's en_US, but I can't verify this, see the edit blow for more information.) to parse, and "100,1" isn't a valid number so the "non-number" part gets stripped off. By specifying a locale that uses "," decimal separators it's capturing the full number properly.
When you NSLog() an NSDecimalNumber it's simply calling -description
, which has no locale context and can print, more or less, whatever it wants.
If you want to print properly formatted numbers use NSNumberFormatter like so:
NSDecimalNumber *number = [NSDecimalNumber decimalNumberWithString:@"100.1"];
NSLog(@"%@", number);
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"fr_FR"];
[formatter setLocale:locale];
NSLog(@"%@", [formatter stringFromNumber:number]);
Or, briefly
NSDecimalNumber *number = [NSDecimalNumber decimalNumberWithString:@"100.1"];
NSLog(@"%@", [NSNumberFormatter localizedStringFromNumber:number numberStyle:NSNumberFormatterDecimalStyle]);
if you just want to use the current locale.
In summary:
-[NSLocale currentLocale]
is a good choice here).Edit:
Ok, I've done some more research on this.
In GNUStep it looks like it ends up using the value for NSDecimalSeparator
in NSUserDefaults
(from a quick browse of their code).
Doing some experimentation I've found that none of the following affect the default parsing behavior, as far as I can tell:
NSDecimalSeparator
in NSUserDefaults
.AppleLocale
in NSUserDefaults
.NSLocaleCode
in NSUserDefaults
.CFBundleDevelopmentRegion
.LANG
/LC_ALL
/etc... values.+[NSLocale systemLocale]
.And obviously it is not +[NSLocale currentLocale]
, as this question stems from the fact that the current locale has no effect.