Kotlin isFinite()

Kotlin isFinite()

In Kotlin, the isFinite() function is used to check if a floating-point number is a finite value (neither infinite nor NaN).

This function is valuable for handling special cases in mathematical calculations where you want to ensure that the result is a valid finite number.

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

Syntax

The syntax of the isFinite() function is:

fun Double.isFinite(): Boolean

The isFinite() function is an extension function for double-precision floating-point numbers and returns true if the number is a finite value, and false otherwise.

Examples for isFinite() function

1. Using isFinite() to Check for Finite Values

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

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 finite? ${result1.isFinite()}")
    println("Is result2 finite? ${result2.isFinite()}")
    println("Is result3 finite? ${result3.isFinite()}")
}

Output

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

In this example, we perform mathematical operations that result in finite value (division by a non-zero number), an infinite value (division by zero), and NaN (Math.sqrt()).

The isFinite() function is used to check if the results are finite, and the outcome is printed.

Summary

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