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

前端 未结 5 898
隐瞒了意图╮
隐瞒了意图╮ 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:11

    maybe you would like to use the non-locale-aware floatval function:

    float floatval ( mixed $var ) - Gets the float value of a string.

    Example from the documentation:

    $string = '122.34343The';
    $float  = floatval($string);
    echo $float; // 122.34343
    
    0 讨论(0)
  • 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"
    
    0 讨论(0)
  • 2021-01-16 09:22

    You can use is_numeric() function to check variable which might contain a number. For example:

    $a = "1.23";
    if (is_numeric($a)) {
        $a = (float)$a;
    }
    
    $b = "1.2 to 1.3";
    if (is_numeric($b)) {
        $b = (float)$b;
    }
    
    var_dump([
        'a' => $a,
        'b' => $b
    ]);
    

    Output

    array (size=2) 'a' => float 1.23 'b' => string '1.2 to 1.3' (length=10)

    0 讨论(0)
  • 2021-01-16 09:29

    You can use the following to check if a string is a float:

    $a = "1.23";
    $isFloat = ($a == (string)(float)$a);
    
    0 讨论(0)
  • 2021-01-16 09:36

    Because it hasn't been mentioned

    if(preg_match('/^\d+\.\d+$/', $string)){
       $float = (float)$string;
    }
    

    I think is_numeric is a better choice, but this works too.

    What I have above only matches floats, so they have to have the decimal. To make that optional use /^\d+(\.\d+)?$/ instead.

    • ^ start of string
    • \d+ one or more digits
    • \. the dot, literally
    • \d+ one or more digits
    • $ end of string

    For the second one /^\d+(\.\d+)?$/ it's the same as the above except with this addition:

    • (...)? optional capture group, match this pastern 0 or 1 times.

    Which it should now be obvious is what makes the decimal optional.

    Cheers!

    0 讨论(0)
提交回复
热议问题