【问题标题】:NSString to NSNumber with some decimal separatorNSString 到 NSNumber 带有一些小数分隔符
【发布时间】:2012-03-20 07:47:54
【问题描述】:

我现在正在构建的应用程序可以“下载”文本文件并从那里获取数字。在模拟器中一切正常,但是当我在设备上测试它时它就崩溃了。过了一会儿,我发现问题出在小数分隔符上。在那个文件中,我使用了.,而我的iPhone 的本地设置需要,。该字符串的示例:

Product 1;100.00
Product 2;82.85
Product 3;95.12
//etc...

将前几个. 更改为, 后,我可以成功运行应用程序,直到它到达第一个.,所以这就是问题所在。

我可以通过编程轻松地将所有 . 替换为 ,但是我希望这个应用程序可以在任何国家使用任何数字格式,而不是将其限制在某些特定市场。

我用来获取这些数字的代码:

NSString *fileContents = [[NSUserDefaults standardUserDefaults]objectForKey:theKey];
NSArray *allLinedStrings = [fileContents componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSMutableArray *allStringNormalized = [NSMutableArray array];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
for (int i = 0; i < allLinedStrings.count; i++) {
    NSString *bla = [allLinedStrings objectAtIndex:i];
    NSArray *bla1 = [bla componentsSeparatedByString:@";"];
    [allStringNormalized addObject:[formatter numberFromString:[bla1 objectAtIndex:1]]];
}
self.values = [NSArray arrayWithArray:allStringNormalized];

任何帮助将不胜感激。

谢谢你:)

【问题讨论】:

    标签: objective-c ios decimal nsnumber nsnumberformatter


    【解决方案1】:

    如果我对问题的理解正确,您希望NSNumberFormatter 始终使用. 作为小数分隔符,而不管手机的区域设置如何。解决方法很简单:使用NSNumberFormatter的实例方法setDecimalSeparator:setCurrencyDecimalSeparator:设置小数点分隔符为.

    请注意,您不需要设置两个小数分隔符。如果您的numberStyleNSNumberFormatterDecimalStyle,则使用setDecimalSeparator:;如果您的numberStyleNSNumberFormatterCurrencyStyle,则使用setCurrencyDecimalSeparator:

    更多详情请见the documentation

    【讨论】:

    • 谢谢,这正是我想要的。虽然我希望找到一种使用不同分隔符的方法(如果一个字符串使用.,而其他字符串使用,
    • 您可以对文件运行自动检测。如果你知道,它要么是 .或 ,然后只需查看哪个存在并使用那个。
    猜你喜欢
    • 1970-01-01
    • 2013-03-22
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-13
    相关资源
    最近更新 更多