checking if a number is float in PHP

后端 未结 4 1272
挽巷
挽巷 2020-11-30 14:30

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 no         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 15:03

    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
    

提交回复
热议问题