We have the string "10.6". How to convert such a string to the number 10.6?
|
4 answers
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 catchfor newbies? - Naumov try catchshould be used for real error handling. An emptytry catchunlikely to teach a beginner. - Dmitriy Simushev- Maybe ... In general, if you
try catchto wrap your code intry catchthen 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 catchblock should be used where actual error handling occurs. A typical example: a function throwing a\InvalidArgumentExceptionshould 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) |