Floating Point Equality Checks

Peculiarities of floating point equality and the IEEE standard

Floating Point Comparison

Kotlin follows the IEEE Standard for Floating Point Arithmetic when comparing floating point numbers. However, this only works if the Kotlin compiler is able to statically infer the types of both operands to either Float, Double, or their nullable counterparts Float? and Double?.

If it cannot, Kotlin will fall back to Java’s implementations of equals and compare which don’t adhere to the IEEE standard in two situations:

  • NaN (Not-a-Number) is considered equal to itself, so NaN == NaN.
  • -0.0f is considered less than 0.0f, so -0.0f < 0.0f.

Code Examples

If Kotlin can statically infer the types to Float, it follows the IEEE standard:

Get hands-on with 1400+ tech skills courses.