我在我的代码中的某个地方使用了localizedStringWithFormat:方法在NSString类上将一个7位整数数字转换成一个NSString,现在需要将它转换回一个整数。
因为我的应用程序是针对不同区域本地化的,在三位后有不同的分隔符(例如“.”)。在美国和德国,是将本地化的NSString整数值转换为整数的最佳方法?
我在我的字符串上尝试了integerValue,如下所示,但是它没有工作:
// Somewhere in code:
int num = 1049000;
NSString *myLocalizedNumString = [NSString localizedStringWithFormat:@"%d", num];
// myLocalizedNumString (U.S.): '1,049,000'
// myLocalizedNumString (Germany): '1.049.000'
// Somewhere else where I have a reference to my string but none to the num:
int restoredNum = [myLocalizedNumString integerValue];
// restoredNum isn't 1049000 (it's 0, the initial value)做这件事的好方法是什么?
发布于 2013-07-04 19:41:30
尽管它的名称NSNumberFormatter是双向转换的,但它还是一个字符串解析器。在将number格式化程序的numberStyle属性设置为NSNumberFormatterDecimalStyle之后,使用方法NSNumberFormatterDecimalStyle解决了您的问题。
代码可能如下所示:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSInteger restoredNum = [[formatter numberFromString:myLocalizedNumString] integerValue];https://stackoverflow.com/questions/17477169
复制相似问题