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

String 在swift 3中将字符串转换为精度为2的双精度字符串?,string,swift3,double,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”).roundT

嗨,我正在尝试转换一个精度为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(位置:2)
转换为123.0。有什么可能的方法可以做到这一点吗?提前谢谢

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

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
请注意,如果Double实际上只有零作为小数,则不会显示它们。当您将格式转换回字符串时,需要使用格式设置程序来显示它们。请尝试以下操作:

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
请注意,如果Double实际上只有零作为小数,则不会显示它们。当您将其转换回字符串时,需要使用格式化程序来显示它们

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

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

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

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