PHP check if variable is a whole number

后端 未结 20 970
感动是毒
感动是毒 2020-12-29 20:05

I have this PHP code:

$entityElementCount = (-($highScore-$totalKeywordCount))/0.29;

What i want to know is, how to check whether $

20条回答
  •  礼貌的吻别
    2020-12-29 20:34

    function isInteger($value)
    {
        // '1' + 0 == int, '1.2' + 0 == float, '1e2' == float
        return is_numeric($value) && is_int($value + 0);
    }
    
    function isWholeNumber($value)
    {
        return is_numeric($value)
            && (is_int($value + 0)
                || (intval($value + 0) === intval(ceil($value + 0))));
    }
    

    If you want to check for both whole and decimal numbers, you can do the following:

    if (isInteger($foo))
    {
        // integer as int or string
    }
    if (isWholeNumber($foo))
    {
        // integer as int or string, or float/double with zero decimal part
    }
    else if (is_numeric($foo))
    {
        // decimal number - still numeric, but not int
    }
    

    This will correctly check your number without rounding it, casting it to int (which in the case of a decimal number will lose the decimal part), or doing any math. If, however, you want to treat 1.00 as a whole number, then that's a whole another story.

提交回复
热议问题