如何将数字字符引用转换为 Swift 中的小数?

How to convert a numeric character reference to a decimal in Swift?

如何将这种类型的字符串"8.37"转换成它的十进制值8.37? 我正在使用 Swift 4.

我试过了:

extension String {

func hexToFloat() -> Float {
    var toInt = Int32(truncatingIfNeeded: strtol(self, nil, 16))
    var float:Float32!
    memcpy(&float, &toInt, MemoryLayout.size(ofValue: float))
    return float
}
}

[...]

let myString = "8.37"
let myDecimal = myString.hexToFloat()
print(myDecimal) // prints 0.0

(From here)

没有直截了当的方法(至少据我所知)。但是你可以做类似下面的事情来获得价值。请注意下面的代码在Swift3中。您可能需要更改语法。

extension String {    
    func hexToFloat() -> Float {
        let data = myString.data(using: .utf8)
        let options: [String: Any] = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
        do {
            let attributedString = try NSAttributedString(data: data!, options: options, documentAttributes: nil)
            return Float(attributedString.string)!
        } catch {
            return 0
        }
    }
}

let myString = "8.37"
let myDecimal = myString.hexToFloat()
print(myDecimal) // prints 8.37