Mastering PHP’s floatval: Convert Any Variable to Float Easily
This guide explains how PHP's built‑in floatval function converts integers, strings, booleans, and arrays into floating‑point numbers, provides syntax and practical code examples, and highlights important considerations when conversion fails.
In PHP we often need to cast variables to floating‑point numbers, and the built‑in floatval function makes this straightforward.
Syntax
floatval ( mixed $var ) : floatThe function accepts any variable—integer, string, boolean, array, etc.—and attempts to convert it to a float, returning the result.
Examples
// Convert an integer
$int = 10;
$float = floatval($int);
echo $float; // 10.0
echo gettype($float); // double
// Convert a numeric string
$str = "3.14";
$float = floatval($str);
echo $float; // 3.14
echo gettype($float); // double
// Convert a string with extra characters
$str = "3.14test";
$float = floatval($str);
echo $float; // 3.14
echo gettype($float); // double
// Convert a boolean
$bool = true;
$float = floatval($bool);
echo $float; // 1.0
echo gettype($float); // double
// Convert an array (first element is used)
$arr = [5, 10, 15];
$float = floatval($arr);
echo $float; // 5.0
echo gettype($float); // doubleThese examples show that integers, numeric strings, booleans, and even arrays can be easily turned into floats with floatval.
Be aware that if the value cannot be interpreted as a number—e.g., a non‑numeric string— floatval returns 0, so you should validate inputs before conversion.
In summary, floatval is a handy tool for converting variables to floating‑point numbers, useful in calculations, monetary operations, and other numeric processing tasks.
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.
