tags:

views:

29

answers:

1

I have this

$number = 0.5

if (is_float($number))
{
  echo 'float';
}
else
{
  echo 'not float';
}

and it echos not float. what could be the reason thanks

+2  A: 

Probably $number is actually a string: "0.5".

See is_numeric instead. The is_* family checks against the actual type of the variable. If you only what to know if the variable is a number, regardless of whether it's actually an int, a float or a string, use is_numeric.

If you need it to have a non-zero decimal part, you can do:

//if we already know $number is numeric...
if ((int) $number == $number) {
    //is an integer
}
Artefacto
if its a string then how would I distinguish between an integer and the float point in the sting?thanks
@user I've edit the response in order to address your concerns.
Artefacto
Casting it to an int wouldn't help if you want to check for floats. Also, you should be using [`intval`](http://ca.php.net/manual/en/function.intval.php) or [`floatval`](http://ca.php.net/manual/en/function.floatval.php) to convert a string to a number.
Daniel Vandersluis
@Daniel Yes, you can... if it's numeric and it's not an int, then it's a float (it's else branch for the if above). See http://codepad.viper-7.com/yqJ75c As to `intval` et al... it's a micro optimization.
Artefacto