【问题标题】:convert string to double gives nil将字符串转换为双精度给出 nil
【发布时间】:2018-10-30 09:55:36
【问题描述】:

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

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

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

这里是sn-p的代码:

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 始终为零。

这里发生了什么?

【问题讨论】:

  • 显示print(latString.debugDescription)的输出
  • latString.debugDescription 显示 "\"40.426687899755734\""
  • 有你的答案:数字用引号括起来。 – 顺便说一句,你为什么对属性字符串而不是原始内容进行操作?输入文件格式是什么?
  • 啊当然。感谢那!这是正确的答案。

标签: swift string casting double


【解决方案1】:

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

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 阅读器库 你可以试试。

【讨论】:

    猜你喜欢
    • 2011-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多