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

我有:

var totalWorkTimeInHours = (totalWorkTime/60/60)

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

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

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


当前回答

基于Yogi的回答,这里有一个Swift函数来完成这项工作:

func roundToPlaces(value:Double, places:Int) -> Double {
    let divisor = pow(10.0, Double(places))
    return round(value * divisor) / divisor
}

其他回答

斯威夫特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)

使用内置的达尔文基金会图书馆

斯威夫特3

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

用法:

let number:Double = 12.987654321
print(number.round(to: 3)) 

输出:12.988

对于许多应用程序,需要精确的小数位数来舍入。

对于其他一些,您没有这样的限制,并希望“压缩”输出大小,但仍然希望避免将数字转换为字符串(反之亦然),就像导出具有数百万个数字的JSON一样。

在这种情况下,你可以使用'trick'来四舍五入显数(尾数),而不是整数。在这种情况下,你会得到最后的小数点 大多数数字仍然最多保留3位小数点后(如果需要的话),而有些数字会稍微多一些。

这是你在使用十进制数时所期望的结果:

5.2472 5.2516 5.2556 5.26 5.264

而不是:

5.24731462499949 5.251488374999099 5.25566283399894 5.259839374999501 5.264012208999702

let value = 5.24731462499949

print(value)
// 5.24731462499949

let valueSignificandRounded = round((1000 * 10) * value.significand) / (1000 * 10)

let valueRounded = CGFloat(sign: v.sign, exponent: v.exponent, significand: valueSignificandRounded)

print(valueRounded)
// 5.2472

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

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

Lots of example are using maths, the problem is floats are approximations of real number, there is no way to express 0.1 (1/10) exactly as a float just as there is no exact way to express ⅓ exactly using decimal points, so you need to ask your self exactly what your are trying to achieve, if you just want to display them leave them as they are in code, trying to round them is going to justify give you less accurate result as you are throwing away precious, round ⅓ in decimal notation to 1 decimal place is not going to give you a number closer to ⅓, us NumberFormate to round it, if you have something like a viewModel class it can be used to return a string representation to your models numbers. NumberFormaters give you lots of control on how numbers are formatted and the number of decimal places you want.