floatval() function is a built-in function in PHP that converts a variable to a float (floating-point) number. It is similar to the
doubleval() function, which also converts a variable to a float.
The syntax of the
floatval() function is as follows:
float floatval(mixed $var)
The function takes a single parameter,
$var, which is the variable to be converted to a float. The function returns the float value of the variable, or 0.0 if the variable cannot be converted.
Here is an example of how to use the
floatval() function in PHP:
$var1 = "3.14159"; $var2 = 42; $var3 = true; $var4 = "not a number"; echo floatval($var1) . "\n"; // output: 3.14159 echo floatval($var2) . "\n"; // output: 42.0 echo floatval($var3) . "\n"; // output: 1.0 (true is converted to 1.0) echo floatval($var4) . "\n"; // output: 0.0 (cannot convert "not a number" to a float)
In this example, we define four variables with different data types:
$var1 is a string,
$var2 is an integer,
$var3 is a boolean, and
$var4 is a string that cannot be converted to a float. We then use the
floatval() function to convert each variable to a float and output the result. The output shows the float value of each variable, or 0.0 if the variable cannot be converted.
floatval() function is a useful tool for converting a variable to a float (floating-point) number in PHP. It can be used to convert strings, integers, and booleans to floats, among other data types. By using this function, developers can ensure that their code is working with the correct data types and avoid errors that may occur when working with mixed data types.