I have this PHP code:
$entityElementCount = (-($highScore-$totalKeywordCount))/0.29;
What i want to know is, how to check whether $
I always use typecasting to check if variables contain a whole number, handy when you don't know the origin or type of the value.
if ((string) $var === (string) (int) $var) {
echo 'whole number';
} else {
echo 'whatever it is, it\'s something else';
}
In your particular case, I would use is_int()
if (is_int($var) {
echo 'integer';
}
if (floor($number) == $number)
I know this is a super old post but this is a simple function that will return a valid whole number and cast it to an int. Returns false if it fails.
function isWholeNumber($v)
{
if ($v !='' && is_numeric($v) && strpos($v, '.') === false) {
return (int)$v;
}
return false;
}
Usage :
$a = 43;
$b = 4.3;
$c = 'four_three';
isWholeNumber($a) // 43
isWholeNumber($b) // false
isWholeNumber($c) // false
$num = 2.0000000000001;
if( $num == floor( $num ) ){
echo('whole');
}else{
echo('fraction');
}
EX:
2.0000000000001 | fraction
2.1 | fraction
2.00 | whole
2 | whole
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
$entityElementCount = (-($highScore-$totalKeywordCount))/0.29;
Method 1-
By using ctype_digit() function.
if ( ctype_digit($entityElementCount )) {
echo "Whole Number\n";
} else {
echo "Not a whole Number\n";
}
Method 2-
By using is_float() function.
if (is_float($entityElementCount )) {
echo "Not a Whole Number\n";
} else {
echo "Whole Number\n";
}
Method 3-
By using is_int() function.
if (is_int($entityElementCount )) {
echo "Whole Number\n";
} else {
echo "Not a whole Number\n";
}
Method 5-
By using fmod() function.
It needs 2 parameters one dividend and other is divisor
Here $dividend=$entityElementCount and divisor=1
if (fmod($dividend,$divisor) !== 0.0) {
echo 'Not a whole number!';
} else {
echo 'A whole number!';
}
there are some more function like intval(), floor(),... can be used to check it`enter code here`