wrong decimal separator with NSDecimalNumber in iOS

China☆狼群 提交于 2019-12-06 04:38:55

问题


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!



来源:https://stackoverflow.com/questions/9093646/wrong-decimal-separator-with-nsdecimalnumber-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!