Floating Point Equality Checks
Peculiarities of floating point equality and the IEEE standard
We'll cover the following...
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, soNaN == NaN
.-0.0f
is considered less than0.0f
, so-0.0f < 0.0f
.
Code Examples
If Kotlin can statically infer the types to Float
, it follows the IEEE standard:
Access this course and 1400+ top-rated courses and projects.