Reputation: 23498
We are communication with a server that sends back numbers in the format: "$229,000"
.
We use NSNumberFormatter
to convert this into a number like:
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.
However, on iOS-10 the above code will fail unless we add the currency symbol as "$"
.
Is there any other solutions other than checking iOS version (via NSFoundationVersionNumber
)?
Upvotes: 0
Views: 441
Reputation: 318774
Your code can be made to work on all versions of iOS by changing it as follows:
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:
.
Tested with iOS 10, 9.3, and 8.4.
Upvotes: 2