Using PHP’s floatval() Function to Convert Variables to Float
This article explains PHP’s built‑in floatval() function, its syntax, and provides multiple code examples showing how to convert integers, strings, booleans, and arrays to floating‑point numbers, while also noting conversion limitations such as non‑numeric strings returning zero.
In PHP, we often need to convert variables to floating‑point type. This is useful for numeric calculations, monetary transactions, and similar scenarios. PHP provides a built‑in function called floatval that can quickly convert variables to a float.
The syntax of the floatval function is as follows:
floatval ( mixed $var ) : floatThe function accepts one parameter $var , which can be any PHP variable such as an integer, string, etc. It attempts to convert this variable to a float and returns the converted result.
Below are example codes demonstrating how to use floatval to convert different types of variables to float:
// Convert an integer to float
$int = 10;
$float = floatval($int);
echo $float; // output: 10.0
echo gettype($float); // output: double
// Convert a numeric string to float
$str = "3.14";
$float = floatval($str);
echo $float; // output: 3.14
echo gettype($float); // output: double
// Convert a string with extra characters to float
$str = "3.14test";
$float = floatval($str);
echo $float; // output: 3.14
echo gettype($float); // output: double
// Convert a boolean to float
$bool = true;
$float = floatval($bool);
echo $float; // output: 1.0
echo gettype($float); // output: double
// Convert an array to float (the first element is used)
$arr = [5, 10, 15];
$float = floatval($arr);
echo $float; // output: 5.0
echo gettype($float); // output: doubleFrom the examples, regardless of whether the input is an integer, string, boolean, or array, the floatval function can conveniently convert it to a floating‑point number.
Note that if a variable cannot be converted to a float—e.g., a string containing non‑numeric characters— floatval will return 0. Therefore, ensure the variable’s type and value are as expected before using the function.
In summary, PHP’s floatval function helps quickly convert variables to float. It is very practical for numeric calculations, monetary transactions, and similar tasks. We hope this guide enables readers to better understand and apply the floatval function.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.