Using PHP floatval() to Convert Variables to Float
This article explains PHP's built‑in floatval() function, showing its syntax, how it converts various variable types—including integers, strings, booleans, and arrays—to floating‑point numbers, provides multiple code examples, and notes edge cases where conversion fails, offering a concise guide for developers.
In PHP, we often need to convert variables to a floating‑point type. This is useful for numeric calculations, currency transactions, and other scenarios. PHP provides a built‑in function called floatval that can quickly convert a variable to a float.
The syntax of the floatval function is:
floatval ( mixed $var ) : floatThis function accepts a single parameter $var , which can be any PHP variable such as an integer, string, etc. It attempts to convert the variable to a floating‑point number and returns the result.
Below are several code examples demonstrating how to use floatval to convert different kinds 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 (non‑numeric part is ignored)
$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 of the array is used)
$arr = [5, 10, 15];
$float = floatval($arr);
echo $float; // output: 5.0
echo gettype($float); // output: doubleFrom the examples above, 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—for example, a string containing non‑numeric characters— floatval will return 0. Therefore, before using the function, ensure that the variable’s type and value are as expected.
In summary, the PHP function floatval helps quickly convert variables to floating‑point numbers. It is very practical for numeric calculations, currency transactions, and similar tasks. We hope this article enables readers to better understand and apply the floatval function.
PHP8 Video Tutorial
Scan the QR code to receive free learning materials
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.