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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With