在Swift 3中将String转换为精度2加倍?

时间:2017-07-10 14:59:14

标签: string swift3 double

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

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

转换Double("123.0000").roundTo(places: 2),但我的结果为123.0。有没有可行的方法呢?提前谢谢。

注意:我尝试使用字符串格式和nsstring方法

失败

2 个答案:

答案 0 :(得分:4)

Try this out

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

if let roundedOffNumber = Double("12.0000")?.roundTo(places: 2) {
    print(roundedOffNumber)
}

答案 1 :(得分:1)

Try this:

extension Double {
    func roundTo(places:Int) -> Double {
        let string = String(format: "%\(Double(places)/10.0)f", self)
        return Double(string) ?? self // If the string was not correct and the conversion to double failed, simply return the non formatted version
    }
}

var test:Double = 123.34556

test.roundTo(places:3) // Double is now 123.345

Note that if the Double actually has only zeros as decimals, it will not show them. You'll need to use a formatter to display them when you convert it back to a string