Checking if number is float in PHP

This is really weird. I have this piece of code.

$rewardAmt = $amt;
if(is_float($rewardAmt)){
      print_r("is float");die;
} else {
      print_r("is not float"); die;
}

      

the $ amt value is 0.01. But it goes over to another condition. So I did var_dump $ amt. it says line (4) So I decided to come up with $ amt

   $rewardAmt = (float)$amt;

      

But the problem with that is even if the value of $ amt is 1, it still gets the typecast for the float and goes into the if condition, which it shouldn't. Is there any other way to do this? Thanks to

+3


source to share


4 answers


If you change the first line to

$rewardAmt = $amt+0;

      



$ rewardAmt should be assigned to a number.

+3


source


Use filter_var()

withFILTER_VALIDATE_FLOAT



if (filter_var($amount, FILTER_VALIDATE_FLOAT))
{
     // good
}

      

+10


source


You can check it out at

$float = floatval($num); //Convert the string to a float
if($float && intval($float) != $float) // Check if the converted int is same as the float value...
{
    // $num is a float
}else{
    // $num is an integer
}

      

0


source


You can use the unary operator +

, which will pass a string to the appropriate type ( int

or float

), and then check the resulting data type with is_float

:

$s = "3.00";
$n = +$s;
var_dump( $n ); // float(3)
var_dump( is_float($n) ); // true


$s = "3";
$n = +$s;
var_dump( $n ); // int(3)
var_dump( is_float($n) ); // false

      

0


source







All Articles