将不带分隔符的字符串转换为Double / CLLocationDegrees

问题描述 投票:0回答:1

我有很多像“9904962”和“57053717”这样的字符串我需要将它们转换为CLLocationDegrees以用于创建CLLocation对象。

问题是缺少逗号/标点符号。

我可以做字符计数并设置标点符号,如下所示:

var coordinateString = "57053717"

let offset = coordinateString.characters.count > 7 ? 2 : 1

coordinateString.insert(".", at: coordinateString.index(coordinateString.startIndex, offsetBy: offset))

那么我的coordinateString将是“57.053717”或“9.904962”

但我不认为这是最好的解决方案,这仅涵盖原始字符串长于或短于7个字符的情况。

什么是更好的解决方案?

swift double cllocation
1个回答
0
投票

Swift3.0

let numberString: NSMutableString = "57053717" // Convert string to MutableString

let offset = numberString.characters.count > 7 ? 2 : 1 // finding offset value

numberString.insert(".", at: offset) // insert "." in offset index
print(numberString)

let doubled = numberString.doubleValue // convert to double vale
print(doubled)

输出:57.053717

© www.soinside.com 2019 - 2024. All rights reserved.