在 swift 3 中将字符串转换为精度为 2 的双精度?

e.k*_*e.k 1 string double swift3

您好,我正在尝试将 4 个精度的字符串(例如 12.0000)转换为 12.00。为此,在搜索谷歌后,我正在使用代码

extension Double {
    func roundTo(places:Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return (self * divisor).rounded() / divisor
    }
}
Run Code Online (Sandbox Code Playgroud)

进行转换Double("123.0000").roundTo(places: 2),但我得到的结果为 123.0.0. 有没有可能的方法来做到这一点?提前致谢。

注意:我尝试了字符串格式和 nsstring 方法,但失败了

Raj*_*ari 5

试试这个

extension Double {
    func roundTo(places:Int) -> String {
        return String(format: "%.\(places)f", self)
    }
}

if let roundedOffNumber = Double("12.0000")?.roundTo(places: 2) {
    print(roundedOffNumber)
}
Run Code Online (Sandbox Code Playgroud)