Home > Software design >  Extract Double Value from String in Swift
Extract Double Value from String in Swift

Time:04-20

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.

CodePudding user response:

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)
}
  • Related