首页 > 解决方案 > Swift 指定双精度而不转换为字符串

问题描述

我想将我的(滑块)指定为 2 位小数,但 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
  }
}

标签: swiftdouble

解决方案


这应该做你需要的:

extension Double {
    func roundedTo(places: Int) -> Double {
        let conversion = pow(10.0, Double(places))
        return (self * conversion).rounded() / conversion
    }
}

print(10.125.roundedTo(places: 2)) // prints 10.13
print(10.124.roundedTo(places: 2)) // prints 10.12

推荐阅读