[英]iOS 10 NumberFormatter returns NIL but works on iOS9, iOS8, iOS7
We are communication with a server that sends back numbers in the format: "$229,000"
. 我们正在与一台服务器通信,该服务器以以下格式发送回数字:
"$229,000"
。
We use NSNumberFormatter
to convert this into a number like: 我们使用
NSNumberFormatter
将其转换为数字,例如:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[formatter setCurrencyCode:@"US"];
[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
[formatter setCurrencySymbol:@""];
On any iOS version BELOW iOS-10GM, currency symbol has to be empty string or nil otherwise the formatter fails and returns nil. 在低于iOS-10GM的任何iOS版本上,货币符号必须为空字符串或nil,否则格式化程序将失败并返回nil。
However, on iOS-10 the above code will fail unless we add the currency symbol as "$"
. 但是,在iOS-10上,除非我们将货币符号添加为
"$"
否则上述代码将失败。
Is there any other solutions other than checking iOS version (via NSFoundationVersionNumber
)? 除了检查iOS版本(通过
NSFoundationVersionNumber
)以外,还有其他解决方案吗?
Your code can be made to work on all versions of iOS by changing it as follows: 通过更改代码,可以使您的代码在所有版本的iOS上都可以使用:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
There is no need to set the currency code or symbol since the string you are parsing is already appropriate for the locale being set. 无需设置货币代码或符号,因为您要分析的字符串已经适合于所设置的语言环境。
That code will now properly give a valid NSNumber
when passing @"$229,000"
to numberFromString:
. 现在,在将
@"$229,000"
传递给numberFromString:
时,该代码将正确地提供有效的NSNumber
。
Tested with iOS 10, 9.3, and 8.4. 在iOS 10、9.3和8.4上进行了测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.