Master 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 to floating‑point numbers, provides syntax details, multiple code examples, and important usage notes for reliable numeric handling.
In PHP, converting variables to a floating‑point type is often needed for numeric calculations, monetary transactions, and more. PHP offers the built‑in floatval function to quickly perform this conversion.
The syntax of floatval is: floatval ( mixed $var ) : float The function accepts a single argument $var, which can be any PHP variable (integer, string, etc.). It attempts to convert the variable to a float and returns the result.
Below are example snippets demonstrating how to use floatval:
// 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 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 (first element is used)
$arr = [5, 10, 15];
$float = floatval($arr);
echo $float; // Output: 5.0
echo gettype($float); // Output: doubleThese examples show that integers, strings, booleans, and arrays can all be conveniently converted to floats using floatval.
Be aware that if a variable cannot be converted—such as a string containing non‑numeric characters— floatval returns 0. Therefore, ensure the variable’s type and value are as expected before calling the function.
In summary, PHP’s floatval function provides a simple and effective way to cast variables to floating‑point numbers, which is especially useful in calculations and financial processing.
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.
