ios – Monetary string to NSNumber NSNumberFormatter doesn’t work for various area

0
12


I’ve a monetary string with I wish to cowl to NSNumber. Earlier than I confronted the problem I did it like that:

extension String { 
 var rawNumber: NSNumber? {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        return formatter.quantity(from: self)
    }
}

After I get the quantity from “5.7” it labored nice on the simulator. Maybe due to United States area.

However actual system with one other area didn’t convert string “5.7” till I relaized that the issue with locale I take advantage of

So I compelled locale a bit and altered the code to this:

extension String {
    
    var rawNumber: NSNumber? {
        let numberFormatter = NumberFormatter()
        numberFormatter.locale = Locale(identifier: "en_US")
        numberFormatter.numberStyle = .decimal
        return numberFormatter.quantity(from: self.replacingOccurrences(of: ",", with: "."))
    }

I would like this quantity for function calculation, for instance for multiplying and and many others. I take advantage of NSDecimalNumber for that functions.

So now my code works. Unsure whether it is good to drive locale.

I attempted to make use of numberFormatter.separator as dot and comma for various locale nevertheless it didn’t work for me.

So simply forcing to Locale(identifier: "en_US") works and string might be transformed to NSNnumber

I supposed if I’ll use totally different locales and totally different separators it would convert string to form of NSNumber.double(5.7) no matter I used comma as separator or dot.

I’ve added wanted if block to catch present native and rely upon this I used totally different separators, however no luck.

So seems like Locale(identifier: "en_US") is just an answer right here.

LEAVE A REPLY

Please enter your comment!
Please enter your name here