Master PHP’s floatval: Convert Any Variable to Float Quickly
This guide explains how PHP’s built‑in floatval function converts integers, strings, booleans, and arrays to floating‑point numbers, provides syntax details, showcases practical code examples, and highlights important conversion caveats.
In PHP, converting variables to floating‑point numbers is often needed for numerical calculations, monetary transactions, and more. The built‑in floatval function makes this conversion straightforward.
Syntax
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 variable to a float and returns the result.
Examples
// 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 non‑numeric characters (trailing text 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 is used)
$arr = [5, 10, 15];
$float = floatval($arr);
echo $float; // Output: 5.0
echo gettype($float); // Output: doubleThese examples demonstrate that integers, strings, booleans, and arrays can all be easily converted to floats using floatval.
Note that if a variable cannot be converted to a float—e.g., a string containing non‑numeric characters without a leading number— floatval returns 0. Therefore, ensure the variable’s type and value are appropriate before conversion.
In summary, PHP’s floatval function is a practical tool for quickly converting variables to floating‑point numbers, which is especially useful in numerical computations and financial applications.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
