简体   繁体   中英

checking if a 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;
}

value of $amt is 0.01. But it is going into else condition. So I did a var_dump of $amt. it says string(4) So I decided to typecast $amt

   $rewardAmt = (float)$amt;

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

Use filter_var() with FILTER_VALIDATE_FLOAT

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

If you change the first line to

$rewardAmt = $amt+0;

$rewardAmt should be cast to a number.

You can use the unary + operator, which will cast the string to the appropriate type ( int or float ), and then test 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

You can check this by

$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
}

As suggested in the documentation of is_float function :

Note: To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric() .

The answer is using is_numeric() and not is_float(). This works also if the number tested is "0" or 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM