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

2 Answers

0 votes
$d = 24278.0;

if ($d == floor($d)) {
    echo "The double variable contains an integer","\n";
}
else {
    echo "The double variable contains a floating point","\n";
}



/*
run:
  
The double variable contains an integer
  
*/

 



answered Mar 5, 2024 by avibootz
0 votes
// -----------------------------------------------------------------------------
// Determines whether a double (PHP float) contains an integer (no fractional part).
// Uses a small tolerance to safely handle floating‑point precision issues.
// -----------------------------------------------------------------------------
function isInteger(float $value): bool
{
    $epsilon = 1e-12;

    // floor($value) returns the largest integer <= value
    $floored = floor($value);

    // If the difference is extremely small, treat the number as an integer
    return abs($value - $floored) < $epsilon;
}

// -----------------------------------------------------------------------------
// Prints a descriptive message for the given float.
// -----------------------------------------------------------------------------
function printCheck(float $value): void
{
    // Using sprintf for consistent formatting
    echo "Checking value: " . sprintf("%.15f", $value) . PHP_EOL;

    if (isInteger($value)) {
        echo "Result: The value contains an integer." . PHP_EOL . PHP_EOL;
    } else {
        echo "Result: The value contains a floating‑point number." . PHP_EOL . PHP_EOL;
    }
}

// -----------------------------------------------------------------------------
// Entry point demonstrating several example values.
// -----------------------------------------------------------------------------
function main(): void
{
    // Example input values
    $a = 42.0;                 // integer-like
    $b = 42.00000000001;       // floating-point due to tiny fraction
    $c = 89.0000000000001;     // integer-like
    $d = -7.0;                 // negative integer-like
    $e = 3.14;                 // floating-point

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

main();



/*
run:

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

Checking value: 42.000000000009997
Result: The value contains a floating‑point number.

Checking value: 89.000000000000099
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

...