快速指定双精度而不转换为字符串

问题描述 投票:0回答:1

我想将我的(滑块)指定为两位小数(两位),但是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
  }
}
swift double swiftui specifier
1个回答
0
投票

这应该可以满足您的需求:

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
© www.soinside.com 2019 - 2024. All rights reserved.