wrong decimal separator with NSDecimalNumber in iOS

此生再无相见时 提交于 2019-12-04 10:49:21

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

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!

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