How to check whether a floating-point variable is an integer (has no fractional part) in Kotlin

1 Answer

0 votes
//
// Demonstrates how to check whether a floating‑point value (Double)
// is an integer (has no fractional part) in Kotlin.
// Uses a small tolerance to safely handle floating‑point precision issues.
// Kotlin's Double behaves like a standard IEEE‑754 double.
//

// -----------------------------------------------------------------------------
// Determines whether a Double represents an integer value.
// A tiny epsilon helps avoid floating‑point precision errors.
// -----------------------------------------------------------------------------
fun isInteger(value: Double): Boolean {
    val epsilon = 1e-12

    // floor() returns the largest integer <= value
    val floored = kotlin.math.floor(value)

    // If the absolute difference is extremely small, treat the number as integer
    return kotlin.math.abs(value - floored) < epsilon
}

// -----------------------------------------------------------------------------
// Prints a descriptive message for the given Double.
// -----------------------------------------------------------------------------
fun printCheck(value: Double) {
    println("Checking value: ${"%.15f".format(value)}")

    if (isInteger(value)) {
        println("Result: The value contains an integer.\n")
    } else {
        println("Result: The value contains a floating‑point number.\n")
    }
}

// -----------------------------------------------------------------------------
// Entry point demonstrating several example values.
// -----------------------------------------------------------------------------
fun main() {

    // Example input values
    val a: Double = 42.0                 // integer-like
    val b: Double = 42.00000000001       // floating-point due to tiny fraction
    val c: Double = 89.0000000000001     // integer-like
    val d: Double = -7.0                 // negative integer-like
    val e: Double = 3.14                 // floating-point

    // Run checks
    printCheck(a)
    printCheck(b)
    printCheck(c)
    printCheck(d)
    printCheck(e)
}


/*
run:

Checking value: 42.000000000000000
Result: The value contains an integer.

Checking value: 42.000000000010000
Result: The value contains a floating?point number.

Checking value: 89.000000000000100
Result: The value contains an integer.

Checking value: -7.000000000000000
Result: The value contains an integer.

Checking value: 3.140000000000000
Result: The value contains a floating?point number.

*/

 



answered Sep 10 by avibootz

Related questions

...