PHP: Parsing a string as a float / decimal.

In this tutorial, we will show you how to convert a string into a float or decimal using PHP.

This can be very 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

The deg2rad function threw this warning message because it was expecting a double variable, not a string.

To fix this error, 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.
var_dump($number);

//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.
var_dump($number);

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

Instead of using the floatval function, you can also use type casting.

This is also known as 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 value.