PHP check if variable is a whole number

后端 未结 20 967
感动是毒
感动是毒 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:45

    improved version of @Tyler Carter's solution, which handles edge cases better than the original:

    function is_whole_number($number){
        return (is_float(($f=filter_var($number,FILTER_VALIDATE_FLOAT))) && floor($f)===$f);    
    }
    

    (Tyler's code fail to recognize that the string "123foobar" is not a whole number. this improved version won't make that mistake. credits to @Shafizadeh in the comments for discovering the bug. also this is php7 strict_types=1-compatible)

    0 讨论(0)
  • 2020-12-29 20:47

    The basic way, as Chacha said is

    if (floor($number) == $number)
    

    However, floating point types cannot accurately store numbers, which means that 1 might be stored as 0.999999997. This will of course mean the above check will fail, because it will be rounded down to 0, even though for your purposes it is close enough to 1 to be considered a whole number. Therefore try something like this:

    if (abs($number - round($number)) < 0.0001)
    
    0 讨论(0)
提交回复
热议问题