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

我有:

var totalWorkTimeInHours = (totalWorkTime/60/60)

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

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

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


当前回答

为了避免Float不完美,请使用Decimal

extension Float {
    func rounded(rule: NSDecimalNumber.RoundingMode, scale: Int) -> Float {
        var result: Decimal = 0
        var decimalSelf = NSNumber(value: self).decimalValue
        NSDecimalRound(&result, &decimalSelf, scale, rule)
        return (result as NSNumber).floatValue
    }
}

前女友。 1075.58在使用Float时四舍五入为1075.57 1075.58在使用十进制时四舍五入为1075.58,比例为2和。down

其他回答

这在Swift 5中似乎有效。

令人惊讶的是,现在还没有这样的标准函数。

//用四舍五入截断双位数到小数点后n位

extension Double {

    func truncate(to places: Int) -> Double {
    return Double(Int((pow(10, Double(places)) * self).rounded())) / pow(10, Double(places))
    }

}

:

Using String(format:): Typecast Double to String with %.3f format specifier and then back to Double Double(String(format: "%.3f", 10.123546789))! Or extend Double to handle N-Decimal places: extension Double { func rounded(toDecimalPlaces n: Int) -> Double { return Double(String(format: "%.\(n)f", self))! } } By calculation multiply with 10^3, round it and then divide by 10^3... (1000 * 10.123546789).rounded()/1000 Or extend Double to handle N-Decimal places: extension Double { func rounded(toDecimalPlaces n: Int) -> Double { let multiplier = pow(10, Double(n)) return (multiplier * self).rounded()/multiplier } }

Swift 4, Xcode 10

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

这是一个更灵活的算法舍入到N位有效数字

Swift 3解决方案

extension Double {
// Rounds the double to 'places' significant digits
  func roundTo(places:Int) -> Double {
    guard self != 0.0 else {
        return 0
    }
    let divisor = pow(10.0, Double(places) - ceil(log10(fabs(self))))
    return (self * divisor).rounded() / divisor
  }
}


// Double(0.123456789).roundTo(places: 2) = 0.12
// Double(1.23456789).roundTo(places: 2) = 1.2
// Double(1234.56789).roundTo(places: 2) = 1200

为了避免Float不完美,请使用Decimal

extension Float {
    func rounded(rule: NSDecimalNumber.RoundingMode, scale: Int) -> Float {
        var result: Decimal = 0
        var decimalSelf = NSNumber(value: self).decimalValue
        NSDecimalRound(&result, &decimalSelf, scale, rule)
        return (result as NSNumber).floatValue
    }
}

前女友。 1075.58在使用Float时四舍五入为1075.57 1075.58在使用十进制时四舍五入为1075.58,比例为2和。down