Swift: 如何比较CGFloat小数点后前n位?

Swift: how to compare the first n digits past the decimal place for CGFloat?

如果 A 和 B CGFloats 都等于小数点后 5 位数字,您如何比较?这是必要的,因为 this issue.

与您在任何其他语言中比较浮点数相同。

取数字差的绝对值并将其与您可接受的差值进行比较。

let delta: CGFloat = 0.00001

let a: CGFloat = 3.141592
let b: CGFloat = 3.141593


if abs(a-b) < delta {
    println("close enough for government work")
}

根据@nhgrif 给出的答案,我创建了一些非常易于在存在一些双重比较错误的现有应用程序中使用的东西。

infix operator ~<=
infix operator ~==
infix operator ~>=

extension Double {

    static func ~<= (lhs: Double, rhs: Double) -> Bool {
        (lhs < rhs) || (lhs ~== rhs)
    }

    static func ~>= (lhs: Double, rhs: Double) -> Bool {
        (lhs > rhs) || (lhs ~== rhs)
    }

    static func ~== (lhs: Double, rhs: Double) -> Bool {
        abs(lhs - rhs) < 0.0000000001
    }
}

然后您可以像使用任何其他比较器一样使用它 (1000.0 / 100.0) ~== 10.0 // true