Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check for integer or float values

Tags:

php

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

like image 424
Asim Zaidi Avatar asked Aug 11 '10 18:08

Asim Zaidi


2 Answers

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
}
like image 53
Artefacto Avatar answered Oct 22 '22 14:10

Artefacto


If you are checking just for the .(dot) then you do not need to typecast but manipulate it as a string with [strpos][1]().

if (strpos($number,'.') !== false) {

    echo 'true';
}else {
    echo 'false';
}
like image 37
Noor Avatar answered Oct 22 '22 16:10

Noor