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

我有:

var totalWorkTimeInHours = (totalWorkTime/60/60)

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

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

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


当前回答

斯威夫特5

使用字符串方法

var yourDouble = 3.12345
//to round this to 2 decimal spaces i could turn it into string
let roundingString = String(format: "%.2f", myDouble)
let roundedDouble = Double(roundingString) //and than back to double
// result is 3.12 

但是使用扩展更容易被接受

extension Double {
    func round(to decimalPlaces: Int) -> Double {
        let precisionNumber = pow(10,Double(decimalPlaces))
        var n = self // self is a current value of the Double that you will round
        n = n * precisionNumber
        n.round()
        n = n / precisionNumber
        return n
    }
}

然后你可以使用:

yourDouble.round(to:2)

其他回答

:

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 5中似乎有效。

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

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

extension Double {

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

}

不是斯威夫特,但我相信你明白我的意思。

pow10np = pow(10,num_places);
val = round(val*pow10np) / pow10np;

格式化double属性的最好方法是使用Apple预定义的方法。

mutating func round(_ rule: FloatingPointRoundingRule)

FloatingPointRoundingRule是一个枚举,有以下几种可能

枚举的案例:

案例awayFromZero 四舍五入到最接近的允许值,其大小大于或等于源的大小。

情况下 四舍五入到小于或等于源的最接近的允许值。

案例toNearestOrAwayFromZero 四舍五入到最接近的允许值;如果两个值相等接近,则选择大小较大的值。

案例toNearestOrEven 四舍五入到最接近的允许值;如果两个值相等接近,则选择偶数。

案例towardZero 四舍五入到最接近的允许值,其大小小于或等于源的大小。

情况下了 四舍五入到最接近的允许值,该值大于或等于源。

var aNumber : Double = 5.2
aNumber.rounded(.up) // 6.0

这是一个完整的代码

Swift 3.0/4.0/5.0, Xcode 9.0 GM/9.2及以上

let doubleValue : Double = 123.32565254455
self.lblValue.text = String(format:"%.f", doubleValue)
print(self.lblValue.text)

输出- 123

let doubleValue : Double = 123.32565254455
self.lblValue_1.text = String(format:"%.1f", doubleValue)
print(self.lblValue_1.text)

输出- 123.3

let doubleValue : Double = 123.32565254455
self.lblValue_2.text = String(format:"%.2f", doubleValue)
print(self.lblValue_2.text)

输出- 123.33

let doubleValue : Double = 123.32565254455
self.lblValue_3.text = String(format:"%.3f", doubleValue)
print(self.lblValue_3.text)

输出- 123.326