我想将我的(滑块)指定为两位小数(两位),但是xcode不允许我这样做:
return (Double(pris, specifier: "%.2f"))
而且我不想将其转换为字符串然后对其进行格式化,因为那样就无法读取像600000000这样的数字。
我尝试过类似的解决方案:
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
}
}
这应该可以满足您的需求:
extension Double {
func roundedTo(places: Int) -> Double {
let conversion = pow(10.0, Double(places))
return Double(Int(self * conversion)) / conversion
}
}
print(10.12345.roundedTo(places: 2)) // prints 10.12