user1839862
user1839862

Reputation: 13

convert string to double gives nil

I'm parsing a text file to get the latitude and longitude of locations. I need to convert the lon/lat strings to doubles, but I can't do it.

I've tried both the Double(String) method and the (String as NSNumber).doubleValue. It always gives nil.

When I type in the numbers manually it works.

Here's the code snippet:

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)")
        }

    }

I've looked through the other answers. The type of latString is String, not optional. Trimming white spaces didn't help either. lat is always nil.

What's going on here?

Upvotes: 1

Views: 246

Answers (1)

Martin R
Martin R

Reputation: 539685

Apparently the floating point numbers are enclosed in quotation marks, so you'll need not only trim whitespace but also quotation marks. Example:

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

Further remarks:

  • I do not see the reason to operate on the htmlAttributedString, you probably should split the original content into lines and fields.
  • Is your input a CSV-formatted file? There are open source CSV reader libraries which you might try.

Upvotes: 1

Related Questions