Current Location: Home> Latest Articles> How to avoid the error of judging that floating point numbers are integers when using is_int?

How to avoid the error of judging that floating point numbers are integers when using is_int?

gitbox 2025-05-31

How to avoid errors when using is_int to judge floating point numbers?

If you want to determine whether a floating point number is an integer value, you can use the following methods:

1. Use floor() or ceil() function to compare

If a floating point number is an integer, then its floor() (rounded down) and ceil() (rounded up) should be equal to itself.

Sample code:

 <?php
function isFloatInteger($num) {
    if (!is_float($num)) {
        return false;
    }
    return floor($num) == $num;
}

var_dump(isFloatInteger(3.0));   // bool(true)
var_dump(isFloatInteger(3.5));   // bool(false)
var_dump(isFloatInteger(4));     // bool(false) — 4It&#39;s an integer,Not a floating point number
?>

This code first determines whether it is a floating point number, and then uses floor() to determine whether it is an integer value.

2. Utilize type conversion and comparison

You can convert the floating point number into an integer and then compare whether it is equal to the original value.

 <?php
function isFloatValueInteger($num) {
    return is_float($num) && (int)$num == $num;
}

var_dump(isFloatValueInteger(5.0));  // bool(true)
var_dump(isFloatValueInteger(5.1));  // bool(false)
?>

This method is simple and intuitive.

3. Use filter_var to combine regular expressions

If the variable is of a string type, you can also use a regular expression to determine whether it is an integer represented by floating point.

 <?php
function isFloatStringInteger($str) {
    return preg_match('/^-?\d+\.0+$/', $str) === 1;
}

var_dump(isFloatStringInteger("3.0"));   // bool(true)
var_dump(isFloatStringInteger("3.00"));  // bool(true)
var_dump(isFloatStringInteger("3.1"));   // bool(false)
?>

This is suitable for processing input string data.


Summarize

  • is_int() determines whether the variable type is an integer, and does not determine whether the value itself is an integer.

  • Even if the value of a floating point number is an integer (such as 3.0), it will return false by using is_int() to judge.

  • When you need to determine whether a floating point number is an integer value, you can use floor() , (int) type conversion, or regular expressions and other methods.

  • Select an appropriate method according to the actual scenario to avoid program exceptions due to type judgment errors.

For more PHP related content, please refer to gitbox.net/php-tutorial .