PHP: Parsing a string as a float / decimal.

This is a short PHP tutorial on how to convert a string into a float or decimal variable. This can be important in cases where a PHP function expects a double variable.

Take the following error as an example:

Warning: deg2rad() expects parameter 1 to be double, string given in file.php on line 71

This warning was thrown because PHP’s deg2rad function was given a string variable when it expects a double value.

To fix this, we can simply parse the string as a float value by using the floatval function:

//A string containing a number.
$number = "2.392";

//var_dump it out and you will see that it is
//a string type.

//Use floatval to get the float value
//of our string variable
$number = floatval($number);

//Do another var_dump and you will see that
//it is now a float variable.

In the example above, we essentially extracted the float value from our string variable.

Instead of using the floatval function, you could also use type casting (aka type conversion):

//Using typecasting to parse
//the string as a float.
$number = (float) ($number);

In the example above, we used PHP’s type casting feature to cast our $number string as a float / decimal value.

Hopefully, you found this guide easy and straight-forward!