Comparing two identical Double value return false Swift 3

ios, swift

Solution

Comparing equality in doubles rarely gave you the expected answer this is due to how doubles are stored. You can create custom operators, keeping in mind that you should work with sort of accuracy. To know more you can check this answer, even if it speaks about ObjC the principles are super valid. Since I had the same problem checking online I've found this answer on the apple dev forum. This function should do the trick, you can easily create a custom operator:

func doubleEqual(_ a: Double, _ b: Double) -> Bool {
    return fabs(a - b) < Double.ulpOfOne
}

I've tried to convert from swift 2.x to 3.x it seems that the macro `DBL_EPSILON` is not available anymore.

Problem

I tried to compare two identical latitude, which is of type `Double`, and when I print the result, it's evaluated as `false`. ``` print("spot latitude: " + String(spot.location.latitude)) print("first object: " + String(firstSpot.location.latitude)) print(spot.location.latitude == firstSpot.location.latitude) ``` Output: ``` spot latitude: 32.8842183049047 first object: 32.8842183049047 false ``` Anyone has any idea what's going on?

Original source

Related problems