Oleksandr Matrosov
Oleksandr Matrosov

Reputation: 27113

Getting NSNumber from financial string

I have this extension to get finical string from Double

extension Double {
    static let formatter = NumberFormatter()
    var financialString: String? {
        
        Double.formatter.numberStyle = .decimal
        Double.formatter.maximumFractionDigits = 2
        Double.formatter.minimumFractionDigits = 2
        
        if let result =  Double.formatter.string(for: self) {
            return result
        } else {
            return nil
        }
    }
}

I'm getting 1,001.00 text value from 1001 which is right. One thing that I want to get 1001 back from 1,001.00 now.

Is there a way to get NSNumber from financial string?

Upvotes: 0

Views: 47

Answers (1)

Joshua Smith
Joshua Smith

Reputation: 6621

You could filter the string using a character set and only get the numbers and decimal point back. Then convert that string to a Double.

let characterSet = Set(".0123456789")
Double("$1,001.00".filter(characterSet.contains))

Upvotes: 0

Related Questions