Search code examples
jsonswiftdoublensnumbercllocation

Converting NSNumber to Double(CLLocationDegrees)


I'm trying to add latitude and longitude to annotations on my map. My data is JSON type

 "{\"lat\": 25.0437396, \"lng\": 121.5308224}"

I transform it into a dictionary first

["lat": 25.0437396, "lng": 121.5308224]

and use the value in dictionary to add

var coordinate = CLLocationCoordinate2D()
let latNum = shopCoordinate["lat"] as! NSNumber
let lngNum = shopCoordinate["lng"] as! NSNumber
let lat = latNum as? Double
let lng = lngNum as? Double
coordinate.latitude = lat!
coordinate.longitude = lng!

But the Double type value would become like this, and don't show on map

25.043739599999999, 121.53082240000001

I can't cast it to other type instead, since CLLocationDegrees accepts a double type. It drives my crazy. If someone could give me any advice, I would be really really appreciate it.


Solution

  • Why not simply convert it to a Double directly?

    if let latNum = shopCoordinate["lat"] as? Double, let lngNum = shopCoordinate["lng"] as? Double {
        let coordinate = CLLocationCoordinate2D(latitude: latNum, longitude: lngNum)
    }