Kotlin isNaN()

Kotlin isNaN()

In Kotlin, the isNaN() function is used to check if a floating-point number is “Not a Number” (NaN).

This function is helpful for handling special cases in mathematical calculations where an operation may result in an undefined or non-numeric value.

In this tutorial, we’ll explore the syntax of the isNaN() function and provide examples of its usage in Kotlin.


The syntax of the isNaN() function is:

fun Double.isNaN(): Boolean
fun Float.isNaN(): Boolean

The function returns true if the number is NaN, and false otherwise.


1. Using isNaN() to Check for NaN

In this example, we’ll use isNaN() to check if a result from a mathematical operation is NaN.

Kotlin Program

fun main() {
    val result1 = 10.0 / 5          //2
    val result2 = 10.0 / 0          //Infinity
    val result3 = Math.sqrt(-1.0)   //NaN

    println("result1 : $result1")
    println("result2 : $result2")
    println("result3 : $result3")

    println("Is result1 NaN? ${result1.isNaN()}")
    println("Is result2 NaN? ${result2.isNaN()}")
    println("Is result3 NaN? ${result3.isNaN()}")


result1 : 2.0
result2 : Infinity
result3 : NaN
Is result1 NaN? false
Is result2 NaN? false
Is result3 NaN? true

In this example, we perform three mathematical operations that result in a number, Infinity, and NaN respectively. The isNaN() function is used to check if the results are NaN, and the outcome is printed.


In this tutorial, we’ve covered the isNaN() function in Kotlin, its syntax, and how to use it for checking if a double-precision floating-point number is NaN.