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

我有:

var totalWorkTimeInHours = (totalWorkTime/60/60)

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

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

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


当前回答

:

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 } }

其他回答

你可以添加这个扩展:

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
//find the distance between two points
let coordinateSource = CLLocation(latitude: 30.7717625, longitude:76.5741449 )
let coordinateDestination = CLLocation(latitude: 29.9810859, longitude: 76.5663599)
let distanceInMeters = coordinateSource.distance(from: coordinateDestination)
let valueInKms = distanceInMeters/1000
let preciseValueUptoThreeDigit = Double(round(1000*valueInKms)/1000)
self.lblTotalDistance.text = "Distance is : \(preciseValueUptoThreeDigit) kms"

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

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

你可以使用Swift的round函数来实现这一点。

要对Double进行3位精度的四舍五入,首先将其乘以1000,四舍五入,然后将四舍五入结果除以1000:

let x = 1.23556789
let y = Double(round(1000 * x) / 1000)
print(y) /// 1.236

与任何类型的printf(…)或String(format:…)解决方案不同,此操作的结果仍然是Double类型。

编辑: 关于它有时不能工作的评论,请阅读这篇:每个程序员都应该知道的关于浮点算术的事情

这在Swift 5中似乎有效。

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

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

extension Double {

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

}