谁能告诉我如何在Swift中舍入一个双数值到x位小数点后数位?

我有:

var totalWorkTimeInHours = (totalWorkTime/60/60)

totalWorkTime是一个NSTimeInterval (double),单位为秒。

totalWorkTimeInHours会给我小时数,但它给我的时间量是如此长的精确数字,例如1.543240952039......

当我打印totalWorkTimeInHours时,我如何将其四舍五入到1.543 ?


当前回答

小数点后特定数字的代码为:

var a = 1.543240952039
var roundedString = String(format: "%.3f", a)

这里是%。3f告诉swift将这个数字四舍五入到小数点后3位。如果你想要双倍的数字,你可以使用这个代码:

//字符串为Double

var rounded弦= Double(字符串)(格式:%)。3f”,b型)

其他回答

Swift 4, Xcode 10

yourLabel.text =  String(format:"%.2f", yourDecimalValue)

Swift 2扩展

一个更通用的解决方案是以下扩展,适用于Swift 2和iOS 9:

extension Double {
    /// Rounds the double to decimal places value
    func roundToPlaces(places:Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return round(self * divisor) / divisor
    }
}

Swift 3扩展

在Swift 3中,round被圆润取代:

extension Double {
    /// Rounds the double to decimal places value
    func rounded(toPlaces places:Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return (self * divisor).rounded() / divisor
    }
}

返回Double四舍五入到小数点后4位的示例:

let x = Double(0.123456789).roundToPlaces(4)  // x becomes 0.1235 under Swift 2
let x = Double(0.123456789).rounded(toPlaces: 4)  // Swift 3 version

当我打印totalWorkTimeInHours时,我如何将其四舍五入到1.543 ?

要将totalWorkTimeInHours四舍五入为3位数字以便打印,使用String构造函数,它接受一个格式字符串:

print(String(format: "%.3f", totalWorkTimeInHours))

二重值舍入到小数的x位 不。小数点后的数

var x = 1.5657676754
var y = (x*10000).rounded()/10000
print(y)  // 1.5658 

var x = 1.5657676754 
var y = (x*100).rounded()/100
print(y)  // 1.57 

var x = 1.5657676754
var y = (x*10).rounded()/10
print(y)  // 1.6

你可以添加这个扩展:

extension Double {
    var clean: String {
        return self.truncatingRemainder(dividingBy: 1) == 0 ? String(format: "%.0f", self) : String(format: "%.2f", self)
    }
}

像这样叫它:

let ex: Double = 10.123546789
print(ex.clean) // 10.12