Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading