Ivan
Ivan

Reputation: 705

Converting a String to a Double in Swift (Xcode v 7.0.1)

I am having a surprisingly hard time converting a String to a Double in Swift. Just to give you an overview of what I'm doing, I am parsing an XML file and retrieving values from certain elements. The code looks like this,

var lat = ""
var lati = 0.0

func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {

    if elementName == "lat" {
        self.lat = foundCharacters
        self.lati = (self.lat as NSString).doubleValue
    }

}

When I print self.lat the coordinates get outputted as a String "36.97736". But, when I print self.lati the Double 0.0 gets printed.

I've also tried

self.lat = foundCharacters
let formatter = NSNumberFormatter()
formatter.locale = NSLocale(localeIdentifier: "en_US")
if let decimalAsDoubleUnwrapped = formatter.numberFromString(self.lat)       {
    self.lati = decimalAsDoubleUnwrapped.doubleValue
}

and I get the same result as before.

FIXED: Turns out there were extra white space characters (spaces) being added to the front of "36.97736" and Swift was complaining that the string wasn't of Double format so it was returning nil.

Upvotes: 0

Views: 143

Answers (3)

Joseph Kim
Joseph Kim

Reputation: 35

Use NSNumberFormatter().numberFromString(:)?.doubleValue. So, in context of the snippet you posted:

let foundCharacters = "12.345"
let lat = foundCharacters
var lati: Double

if let doubleFromlat = Double(lat) {
    let lati = NSNumberFormatter().numberFromString(foundCharacters)?.doubleValue
 } else {
    print("foundCharacters does not hold double")
 } 

Upvotes: 0

Jeef
Jeef

Reputation: 27275

You could try this:

extension String  {

    var asDouble : Double? {
        if let d = Double(self) {
            return d
        }
        return nil
    }
}


let s = "21.5"    
s.asDouble

enter image description here

Upvotes: 0

Lukas
Lukas

Reputation: 3433

In Swift 2.0, you can use Double("String") which returns an optional. Here is how to use it in your code

    lat = foundCharacters //not mentioned in the function btw
    if let doubleFromlat = Double(lat) {
        lati = doubleFromlat
    } else { print("foundCharacters does not hold double") }

Upvotes: 1

Related Questions