How to Convert Any PHP Variable to Float with floatval – Quick Guide
This article explains how PHP's built‑in floatval() function can reliably cast integers, strings, booleans, and arrays to floating‑point numbers, provides clear code examples, and highlights important caveats such as handling non‑numeric strings that result in zero.
In PHP, converting variables to floating‑point numbers is often required for calculations, monetary operations, etc. The built‑in function floatval() performs this conversion.
Syntax: floatval ( mixed $var ) : float. The function accepts any variable type—integer, string, boolean, array, etc.—and attempts to cast 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); // doubleThe examples show that integers, numeric strings, booleans, and even arrays can be turned into floats, with the resulting type always being double in PHP.
Be aware that if the value cannot be interpreted as a number—e.g., a string containing non‑numeric characters only— floatval() returns 0. Therefore, ensure the variable’s content is appropriate before conversion.
In summary, floatval() is a convenient utility for quickly casting variables to floating‑point numbers, useful in numeric calculations 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.
