We have the string "10.6". How to convert such a string to the number 10.6?

    4 answers 4

    For example. This is an explicit conversion.

    $foo ='10.6'; $bar = (float) $foo; 

    But in most cases this is not required by PHP and can itself convert types. More here.

      For a change, I will give an example of how to convert to a floating-point number, with filtering of the source string.

      In most cases, filtering is necessary because PHP will not give an error if you try to convert a string that is not a number representation to a number. Instead, you get 0.0 . (This fact is not at all obvious to newbies.)

      And here is the code:

       $input = '10.6'; // Валидация. if (!filter_var($input, FILTER_VALIDATE_FLOAT)) { throw new \InvalidArgumentException('Неверный формат значения!'); } // Собственно преобразование. $float = (float)$input; 
      • upvote for the code, but don't you think it's worth it to wrap up in a try catch for newbies? - Naumov
      • try catch should be used for real error handling. An empty try catch unlikely to teach a beginner. - Dmitriy Simushev
      • Maybe ... In general, if you try catch to wrap your code in try catch then you can show that this construction handles this exception. And so we can pick it up and not fall into the fatal with uncathing exception - Naumov
      • one
        try catch block should be used where actual error handling occurs. A typical example: a function throwing a \InvalidArgumentException should not handle this exception itself. As for the example, we do not know anything about what level this code belongs to. And if so, then it is logical to give exception handling to the code at the level above. No level above - no exception handler. - Dmitriy Simushev
       $num = "10.6"; $int = (int)$num; $float = (float)$num; 

        Use the floatval function

         $val = "10.6" $var = floatval($val)