gpt4 book ai didi

swift - 将字符串转换为 double 给出 nil

转载 作者:行者123 更新时间:2023-11-28 05:50:42 25 4
gpt4 key购买 nike

我正在解析文本文件以获取位置的纬度和经度。我需要将 lon/lat 字符串转换为 double 字符串,但我做不到。

我已经尝试了 Double(String) 方法和 (String as NSNumber).doubleValue。它总是给零。

当我手动输入数字时,它起作用了。

这是代码片段:

var items = [[String]]()
func readParkingData() {
guard let filepath = Bundle.main.path(forResource: "parking", ofType: "txt") else {
print("file not found")
return
}
print("file path : \(filepath)")

do{
let content = try String(contentsOfFile: filepath, encoding: .utf8)
let attributed = content.htmlAttributedString
let decoded : String = attributed!.string
let split = decoded.split(separator: ";")

var count = 0
var item = [String]()
for word in split {
item.append(String(word))
count += 1
if count == 30 {
items.append(item)
item = [String]()
count = 0
}
}

for entry in items {
print(entry[24])
print(entry[25])
let latString : String = entry[24]
let lonString : String = entry[25]
print(type(of: latString))
let lat = Double(latString)
print(lat)

}

}catch{
print("file read error \(filepath)")
}

}

我浏览了其他答案。 latString 的类型是 String,不是可选的。修剪空格也无济于事。 lat 始终为零。

这是怎么回事?

最佳答案

显然 float 用引号括起来,所以你不仅需要修剪空格,还需要引号。示例:

let latString = "\"12.34\""
print(latString) // "12.34"

var cs = CharacterSet.whitespaces
cs.insert("\"")

let trimmedLatString = latString.trimmingCharacters(in: cs)
print(trimmedLatString) // 12.34

print(Double(trimmedLatString)!) // 12.34

进一步说明:

  • 我没有看到对 htmlAttributedString 进行操作的原因,你可能应该将原始 content 拆分为行和字段。
  • 您输入的是 CSV 格式的文件吗?有开源 CSV 阅读器库你可以试试。

关于swift - 将字符串转换为 double 给出 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53061628/

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