2016-10-17 Compare floats in Swift

To compare floats to zero, or each other, use the following functions:

    func fequal(_ a: Double, _ b: Double) -> Bool {
        return fabs(a - b) < DBL_EPSILON
    }
    func fequal(_ a: Float, _ b: Float) -> Bool {
        return fabs(a - b) < FLT_EPSILON
    }
    func fequal(_ a: CGFloat, _ b: CGFloat) -> Bool {
        return fabs(a - b) < CGFloat(FLT_EPSILON)
    }
    func fequalzero(_ a: Double) -> Bool {
        return fabs(a) < DBL_EPSILON
    }
    func fequalzero(_ a: Float) -> Bool {
        return fabs(a) < FLT_EPSILON
    }
    func fequalzero(_ a: CGFloat) -> Bool {
        return fabs(a) < CGFloat(FLT_EPSILON)
    }

To test, paste the above and the below code in a playground:

    var a: Double = 0.1
    var b: Double = 0.2
    var c: Double = 0.3
    let d = a + b
    if c == d {
        print("Equal!")
    } else {
        print("Not equal")
    }
    if fequal(c, d) {
        print("Equal!")
    } else {
        print("Not equal")
    }