swiftstringnsnumbernumberformatter

In a string with just numbers and commas how do I convert that into a double


So I have a string with just numbers and commas. for example "1,233,323.32"(String) but I want to convert that to 1233323.32(double).


Solution

  • Swift 4: So basically we have a string with commas and we just remove all the commas in the string and then we use NumberFormatter to convert it to a double.

    var newDouble = 0.0
    var string = ""
    string = textField.text?.replacingOccurrences(of: ",", with: "", options: NSString.CompareOptions.literal, range: nil) ?? ""
    let myDouble = NumberFormatter().number(from: string)?.doubleValue
    newDouble = myDouble ?? 0.0
    

    This code only works properly if there are only numbers and commas.