Swift-将值舍入后将值追加到数组

时间:2018-08-20 16:18:50

标签: arrays swift

我正在运行for循环以获取JSON返回的值。我正在更具体地获取纬度值。我正在使用dblLat = (dblLat * 100).rounded() / 100

四舍五入这些值

在将值附加到新Array时,仅将第一个元素正确地四舍五入,然后将每个新元素附加为带小数点后15位的double:

do {
    let json = try JSONSerialization.jsonObject(with: data, options: [])
    //print(json)
    var latArray = [Double]()
    guard let array = json as? [Any] else { return }
    for user in array {
        guard let userDict = user as? [String: Any] else { return }
        guard let userID = userDict["id"] as? Int else { print("No Int Value Present"); return }
        guard let name = userDict["name"] as? String else { return }
        print(name)
        guard let company = userDict["company"] as? [String : String] else { return }
        print(company)
        guard let companyName = company["name"] as? String else { return }
        print(companyName)
        guard let address = userDict["address"] as? [String : Any] else { return }
        guard let geo = address["geo"] as? [String : String] else { return }
        print(geo)
        guard let lat = geo["lat"] as? String else { return }
        guard var dblLat = Double(lat) else { return }
        dblLat = (dblLat * 100).rounded() / 100
        print(dblLat)
        latArray.append(dblLat)
        print(latArray)
        //print(lat)
        print(userID)
    }

} catch {
    print(error)
}

打印数组:

  

[-37.32,-43.950000000000003,-68.609999999999999、29.460000000000001,-31.809999999999999,-71.420000000000002、24.890000000000001,-14.4、24.649999999999999,-38.240000000000002]

1 个答案:

答案 0 :(得分:0)

某些数字的二进制表示形式只是无限的。看看here

您可以使用NumberFormatter来获取具有两位小数位的字符串

let array = [-37.32, -68.609999999999999, 29.460000000000001, -31.809999999999999, -71.420000000000002, 24.890000000000001, -14.4, 24.649999999999999, -38.240000000000002]

let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2

let roundedStringsArray = array.map {formatter.string(from: NSNumber(floatLiteral: $0))!}

print(roundedStringsArray)