Mastering PHP's floatval: Convert Any Variable to a Float
This guide explains how PHP's built‑in floatval function converts integers, strings, booleans, and arrays to floating‑point numbers, shows practical code examples, highlights its return type, and warns about conversion failures when non‑numeric data is provided.
PHP often requires converting variables to floating‑point numbers for calculations or monetary operations, and the built‑in floatval function provides a straightforward way to achieve this.
Function Syntax
The signature is: floatval ( mixed $var ) : float The function accepts any variable type and attempts to cast it to a float, returning the resulting value.
Usage Examples
Below are common scenarios with corresponding code.
// Convert an integer to float
$int = 10;
$float = floatval($int);
echo $float; // 10.0
echo gettype($float); // double
// Convert a numeric string to float
$str = "3.14";
$float = floatval($str);
echo $float; // 3.14
echo gettype($float); // double
// Convert a string with trailing characters
$str = "3.14test";
$float = floatval($str);
echo $float; // 3.14
echo gettype($float); // double
// Convert a boolean to float
$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); // doubleImportant Caveats
If the supplied value cannot be interpreted as a number—e.g., a string containing non‑numeric characters without a leading numeric part— floatval returns 0. Therefore, callers should validate or sanitize inputs before casting.
Conclusion
The floatval function is a handy tool for quickly turning various PHP variable types into floats, making it valuable for numeric computation, financial processing, and any context where precise decimal representation is required.
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.
