Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP check if variable is a whole number

I have this PHP code:

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

What i want to know is, how to check whether $entityElementCount is a whole number (2, 6, ...) or partial (2.33, 6.2, ...).

Thank you!

like image 228
spacemonkey Avatar asked Feb 02 '10 23:02

spacemonkey


People also ask

How do you check if a number is whole in PHP?

if y is anything other then a whole number the result is not a zero (0). A test then would be: if (y % 1 == 0) { // this is a whole number } else { // this is not a whole number } var isWhole = (y % 1 == 0? true: false); // to get a boolean return.

How can I check if a variable is numeric in PHP?

The is_numeric() function checks whether a variable is a number or a numeric string. This function returns true (1) if the variable is a number or a numeric string, otherwise it returns false/nothing.

How do you check if a variable is an integer?

Using int() function The function int(x) converts the argument x to an integer. If x is already an integer or a float with integral value, then the expression int(x) == x will hold true. That's all about determining whether a variable is an integer or not in Python.

How do you check if a string is a number PHP?

To check if given string is a number or not, use PHP built-in function is_numeric(). is_numeric() takes string as an argument and returns true if the string is all numbers, else it returns false.


2 Answers

I know this is old, but I thought I'd share something I just found:

Use fmod and check for 0

$entityElementCount = (-($highScore-$totalKeywordCount))/0.29; if (fmod($entityElementCount,1) !== 0.0) {     echo 'Not a whole number!'; } else {     echo 'A whole number!'; } 

fmod is different from % because if you have a fraction, % doesn't seem to work for me (it returns 0...for example, echo 9.4 % 1; will output 0). With fmod, you'll get the fraction portion. For example:

echo fmod(9.4, 1);

Will output 0.4

like image 23
Joseph Avatar answered Sep 21 '22 21:09

Joseph


if (floor($number) == $number) 
like image 94
Tyler Carter Avatar answered Sep 18 '22 21:09

Tyler Carter