gpt4 book ai didi

arrays - Swift - 在舍入值后将值附加到数组

转载 作者:行者123 更新时间:2023-11-30 11:13:39 24 4
gpt4 key购买 nike

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

对值进行舍入

将值附加到新数组时,只有第一个元素会正确附加为四舍五入,此后每个新元素都会附加为具有 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]

最佳答案

某些数字的二进制表示形式是无限的。看看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)

关于arrays - Swift - 在舍入值后将值附加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51934822/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com