Search code examples
iosswiftstringxcodedouble

Extract Double Value from String in Swift


I am using location to access the current temperature in my app. I got the weather temperature but I need only double value from it.

let weatherTemp = "41.7°C"

The required thing is:

weatherTemp = 41.7

How can I do that? I used:

extension Double {
    static func parse(from string: String) -> Double? {
        return Double(string.components(separatedBy: CharacterSet.decimalDigits.inverted).joined())
    }
}

This prints all the digits but not the decimal. I need the decimal too.


Solution

  • Split the string on the '°' and convert the first part to Double

    if let tempString = weatherTemp.split(separator: "°").first, let temp = Double(tempString) {
        print(temp)
    }