PHP: convert string to float (only if string represents a float)

前端 未结 5 952
隐瞒了意图╮
隐瞒了意图╮ 2021-01-16 08:59

I have an unknwon string that could resemble a float. In that case I want to convert it to float (for calculations), otherwise leave it as a string.

5条回答
  •  孤城傲影
    2021-01-16 09:16

    function StrToFloat($var){
        if(is_numeric($var)){
            return (float)$var;
        } else return $var;
    } 
    
    $a = "1.23";        // convert $a to 1.23
    $b = "1.2 to 1.3";  // leave $b as is
    
    $a = StrToFloat($a); // $a = 1.23
    $b = StrToFloat($b); // $b = "1.2 to 1.3"
    

提交回复
热议问题