Swift 3.0 Converting String to Double returning nil?

aggnt

Trying to do something so simple but it's simply not working for me.

CODE:

let long = index["Longitude"] as! String
let lat = index["Latitude"] as! String

print(long as Any)
print(lat as Any)

let doubleLong = Double(long)
print(doubleLong as Any)

DEBUG OUTPUT:

-85.1113644443208 
32.880541654362 
nil

^^^ Why so nil? I will add this is being pulled from a JSON Response. Perhaps this has something to do with it.

Sulthan

Most likely there is an additional space in your data, note:

print(Double("-85.1113644443208")) // => Optional(-85.111364444320799)
print(Double("-85.1113644443208 ")) // => nil
print(Double(" -85.1113644443208")) // => nil

Try to trim the spaces first:

let doubleLong = Double(long.trimmingCharacters(in: CharacterSet.whitespaces))

or use a NumberFormatter for parsing:

let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.locale = Locale(identifier: "en_US_POSIX")

print(numberFormatter.number(from: "-85.1113644443208") as Double?) // => Optional(-85.111364444320799)
print(numberFormatter.number(from: " -85.1113644443208") as Double?) // => Optional(-85.111364444320799)
print(numberFormatter.number(from: "-85.1113644443208 ") as Double?) // => Optional(-85.111364444320799)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related