【问题标题】:Convert back localized NSString number (> 4 digits) to integer将本地化的 NSString 数字(> 4 位)转换回整数
【发布时间】:2013-07-04 19:37:03
【问题描述】:

我在NSString 类上使用localizedStringWithFormat: 方法将一个七位整数转换为我代码中某处的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)

什么是好的工作方式?

【问题讨论】:

  • 所以您不知何故丢失了对原始号码的引用?
  • 没错。我不会问我是否没有;)
  • 然而这是一个运行时问题。那么为什么不能存储原始号码呢?如果您知道格式化的本地化,您可以使用数字格式化程序将其取回。
  • 我已经可以从存储 NSString 值的 UI 元素中获取数字,因此我不想存储两次。
  • 这是错误的看待它的方式。您持有的数字实际上是您的模型数据,而字符串将是您的视图表示。你没有拿着它两次,你只有两个不同的东西。您可以从 UI 组件中获取字符串这一事实并不适合存储。

标签: objective-c ios6 type-conversion


【解决方案1】:

尽管它的名字NSNumberFormatter 可以双向转换,但它也是一个字符串解析器。在将数字格式化程序的numberStyle 属性设置为NSNumberFormatterDecimalStyle 后使用方法numberFromString 可以解决您的问题。

代码可能如下所示:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; 
formatter.numberStyle = NSNumberFormatterDecimalStyle; 
NSInteger restoredNum = [[formatter numberFromString:myLocalizedNumString] integerValue];

【讨论】:

  • 我尝试了以下方法,但也没有用:NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; [formatter setLocale:[NSLocale currentLocale]]; [formatter setGroupingSeparator:@","]; NSString *valueString = @"1,049,000"; int value = [[formatter numberFromString:valueString] integerValue];
  • 你也需要指定样式,试试加formatter.numberStyle = NSNumberFormatterDecimalStyle;
  • 谢谢,numberStyle 甚至是我需要设置以使所有工作正常的唯一属性。我的工作代码如下所示:NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; formatter.numberStyle = NSNumberFormatterDecimalStyle; int restoredNum = [[formatter numberFromString:myLocalizedNumString] integerValue];
  • 如果您使用工作示例代码(类似于我上面的代码)更新它,我会接受您的答案。所以其他人可以立即看到完整的代码解决方案。
  • 我很高兴能够提供帮助。查阅课程并找出解决方案是否有助于您理解?与简单地复制预装解决方案相比,您难道不因此而更好吗?
猜你喜欢
  • 1970-01-01
  • 2010-11-11
  • 2019-08-17
  • 1970-01-01
  • 2016-01-03
  • 1970-01-01
  • 2014-04-28
  • 2011-03-10
  • 2013-12-26
相关资源
最近更新 更多