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

1 Answer

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

object DoubleIntegerCheck {

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

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

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

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

    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.
  // ---------------------------------------------------------------------------
  def main(args: Array[String]): Unit = {

    // 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

...