wrong decimal separator with NSDecimalNumber in iO

2020-07-18 05:30发布

问题:

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?

回答1:

@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?



回答2:

You can use this:

NSLocale *locale = [NSLocale currentLocale];

float r = 50/100;

NSString *str = [NSString stringWithFormat:@"%.2f%%", r];
str = [str stringByReplacingOccurrencesOfString:@"." withString:[locale objectForKey: NSLocaleDecimalSeparator]];

It worked!