Using PHP’s floatval Function to Convert Variables to Float
This article explains how PHP’s built‑in floatval function converts various variable types—including integers, strings, booleans, and arrays—into floating‑point numbers, provides syntax details, demonstrates multiple code examples, and notes edge cases such as non‑numeric strings returning zero.
In PHP we often need to convert variables to floating‑point numbers for calculations, monetary transactions, and similar tasks. PHP provides the built‑in floatval function to quickly perform this conversion.
The syntax of floatval is:
floatval ( mixed $var ) : floatThe function accepts a single argument $var , which can be any PHP variable such as an integer, string, boolean, or array. It attempts to convert the value to a float and returns the resulting number.
Examples:
// Convert integer to float
$int = 10;
$float = floatval($int);
echo $float; // Output: 10.0
echo gettype($float); // Output: double
// Convert numeric string to float
$str = "3.14";
$float = floatval($str);
echo $float; // Output: 3.14
echo gettype($float); // Output: double
// Convert string with extra characters
$str = "3.14test";
$float = floatval($str);
echo $float; // Output: 3.14
echo gettype($float); // Output: double
// Convert boolean to float
$bool = true;
$float = floatval($bool);
echo $float; // Output: 1.0
echo gettype($float); // Output: double
// Convert array to float (first element is used)
$arr = [5, 10, 15];
$float = floatval($arr);
echo $float; // Output: 5.0
echo gettype($float); // Output: doubleThese examples show that integers, strings, booleans, and arrays can all be conveniently converted to floats using floatval .
Note that if the variable cannot be converted to a numeric value—e.g., a string containing non‑numeric characters—the function returns 0, so you should ensure the input is appropriate before calling it.
In summary, PHP’s floatval function is a practical tool for quickly converting variables to floating‑point numbers, useful in numerical calculations and monetary processing.
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.