Using PHP floatval() 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, multiple code examples, and notes on conversion edge cases.
In PHP we often need to convert variables to a floating‑point type for numeric calculations, monetary transactions, and similar tasks. The built‑in function floatval() allows us to quickly cast a variable to a float.
The syntax of the function is:
floatval ( mixed $var ) : float
The 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 supplied value to a float and returns the result.
Below are several examples demonstrating how to use floatval() with different kinds of input:
// Convert an integer to float $int = 10; $float = floatval($int); echo $float; // outputs: 10.0 echo gettype($float); // outputs: double // Convert a numeric string to float $str = "3.14"; $float = floatval($str); echo $float; // outputs: 3.14 echo gettype($float); // outputs: double // Convert a string with non‑numeric characters (trailing text is ignored) $str = "3.14test"; $float = floatval($str); echo $float; // outputs: 3.14 echo gettype($float); // outputs: double // Convert a boolean to float (true becomes 1.0, false becomes 0.0) $bool = true; $float = floatval($bool); echo $float; // outputs: 1.0 echo gettype($float); // outputs: double // Convert an array to float (the first element is used) $arr = [5, 10, 15]; $float = floatval($arr); echo $float; // outputs: 5.0 echo gettype($float); // outputs: double
From the examples it is clear that floatval() can conveniently handle integers, numeric strings, booleans, and even arrays (using the first element) when converting to float.
Be aware that if the variable cannot be reasonably converted to a float—such as a string containing non‑numeric characters without a leading number— floatval() will return 0 . Therefore, ensure the variable’s content is appropriate before casting.
In summary, PHP’s floatval() function provides a simple and useful way to cast variables to floating‑point numbers, which is especially handy in numeric computations and financial 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.