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:

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):

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!

Facebook Comments