Reputation: 27113
I have a financial string with I want to cover to NSNumber. Before I faced the issue I did it like that:
extension String {
var rawNumber: NSNumber? {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
return formatter.number(from: self)
}
}
When I get the number from "5.7" it worked great on the simulator. Perhaps because of United States region.
But real device with another region failed to convert string "5.7" until I relaized that the problem with locale I use
So I forced locale a bit and changed the code to this:
extension String {
var rawNumber: NSNumber? {
let numberFormatter = NumberFormatter()
numberFormatter.locale = Locale(identifier: "en_US")
numberFormatter.numberStyle = .decimal
return numberFormatter.number(from: self.replacingOccurrences(of: ",", with: "."))
}
I need this number for feature calculation, for example for multiplying and etc. I use NSDecimalNumber
for that purposes.
So now my code works. Not sure if it is good to force locale.
I tried to use numberFormatter.separator as dot and comma for different locale but it did not work for me.
So just forcing to Locale(identifier: "en_US")
works and string can be converted to NSNnumber
I supposed if I will use different locales and different separators it will convert string to kind of NSNumber.double(5.7)
whatever I used comma as separator or dot.
I've added needed if block to catch current local and depend on this I used different separators, but no luck.
So looks like Locale(identifier: "en_US")
is only a solution here.
Upvotes: 1
Views: 396