谁能告诉我如何在Swift中舍入一个双数值到x位小数点后数位?
我有:
var totalWorkTimeInHours = (totalWorkTime/60/60)
totalWorkTime是一个NSTimeInterval (double),单位为秒。
totalWorkTimeInHours会给我小时数,但它给我的时间量是如此长的精确数字,例如1.543240952039......
当我打印totalWorkTimeInHours时,我如何将其四舍五入到1.543 ?
谁能告诉我如何在Swift中舍入一个双数值到x位小数点后数位?
我有:
var totalWorkTimeInHours = (totalWorkTime/60/60)
totalWorkTime是一个NSTimeInterval (double),单位为秒。
totalWorkTimeInHours会给我小时数,但它给我的时间量是如此长的精确数字,例如1.543240952039......
当我打印totalWorkTimeInHours时,我如何将其四舍五入到1.543 ?
当前回答
一个方便的方法是使用Double类型的扩展
extension Double {
var roundTo2f: Double {return Double(round(100 *self)/100) }
var roundTo3f: Double {return Double(round(1000*self)/1000) }
}
用法:
let regularPie: Double = 3.14159
var smallerPie: Double = regularPie.roundTo3f // results 3.142
var smallestPie: Double = regularPie.roundTo2f // results 3.14
其他回答
基于Yogi的回答,这里有一个Swift函数来完成这项工作:
func roundToPlaces(value:Double, places:Int) -> Double {
let divisor = pow(10.0, Double(places))
return round(value * divisor) / divisor
}
格式化double属性的最好方法是使用Apple预定义的方法。
mutating func round(_ rule: FloatingPointRoundingRule)
FloatingPointRoundingRule是一个枚举,有以下几种可能
枚举的案例:
案例awayFromZero 四舍五入到最接近的允许值,其大小大于或等于源的大小。
情况下 四舍五入到小于或等于源的最接近的允许值。
案例toNearestOrAwayFromZero 四舍五入到最接近的允许值;如果两个值相等接近,则选择大小较大的值。
案例toNearestOrEven 四舍五入到最接近的允许值;如果两个值相等接近,则选择偶数。
案例towardZero 四舍五入到最接近的允许值,其大小小于或等于源的大小。
情况下了 四舍五入到最接近的允许值,该值大于或等于源。
var aNumber : Double = 5.2
aNumber.rounded(.up) // 6.0
:
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.5和Xcode 13.2中:
let pi: Double = 3.14159265358979
String(format:"%.2f", pi)
例子:
附注:自Swift 2.0和Xcode 7.2以来一直如此
在Swift 3.0和Xcode 8.0中:
extension Double {
func roundTo(places: Int) -> Double {
let divisor = pow(10.0, Double(places))
return (self * divisor).rounded() / divisor
}
}
像这样使用这个扩展:
let doubleValue = 3.567
let roundedValue = doubleValue.roundTo(places: 2)
print(roundedValue) // prints 3.56