Search code examples
iosseparatornsdecimalnumbernslocale

wrong decimal separator with NSDecimalNumber in iOS


I tried to output the description of a decimal number with the correct decimal separator in the following way:

NSString* strValue = @"9.94300";
NSDecimalNumber* decimalNumber = [NSDecimalNumber decimalNumberWithString: strValue];    
NSLocale* locale = [NSLocale currentLocale];
NSLog(@"%@", [locale localeIdentifier]);
NSLog(@"%@", [decimalNumber descriptionWithLocale: locale] );

The output is:

de_DE
9.943

The decimal separator should be ',' instead of '.' for this locale. Where is the error? How can I output the correct decimal separator depending on the local?


Solution

  • @TriPhoenix: Yes I'm running iOS 5.

    @Vignesh: Thank you very much. The following code works now if I set the iPhone language to German:

    NSString* strValue = @"9.94300";
    NSDecimalNumber* decimalNumber = [NSDecimalNumber decimalNumberWithString: strValue];    
    NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setFormatterBehavior: NSNumberFormatterBehavior10_4];
    [numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
    NSLog(@"%@", [numberFormatter stringFromNumber: decimalNumber] );
    

    The output is: 9,943

    But now I have another problem. If I switch the iPhone language back to English the output is still 9,943 instead of 9.943. Do I make something wrong?