'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 1:[1]
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)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Joakim Danielson |
