Backend Development 4 min read

Using PHP’s floatval Function to Convert Variables to Float

PHP’s built‑in floatval function converts various variable types—including integers, strings, booleans, and arrays—into floating‑point numbers, returning the numeric value or 0 for non‑numeric strings, making it useful for calculations and monetary operations.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP’s floatval Function to Convert Variables to Float

In PHP, converting variables to floating‑point numbers is common for numerical calculations and monetary transactions. The language provides a built‑in function called floatval ( mixed $var ) : float that quickly casts a variable to a float.

The 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 value to a float and returns the result.

Below are example code snippets demonstrating how to use floatval with different data types:

// Convert an integer to float
$int = 10;
$float = floatval($int);
echo $float;      // outputs: 10.0
echo gettype($float); // outputs: double
// Convert a numeric string to float
$str = "3.14";
$float = floatval($str);
echo $float;      // outputs: 3.14
echo gettype($float); // outputs: double
// Convert a string with extra characters (non‑numeric part is ignored)
$str = "3.14test";
$float = floatval($str);
echo $float;      // outputs: 3.14
echo gettype($float); // outputs: double
// Convert a boolean to float
$bool = true;
$float = floatval($bool);
echo $float;      // outputs: 1.0
echo gettype($float); // outputs: double
// Convert an array (the first element is used)
$arr = [5, 10, 15];
$float = floatval($arr);
echo $float;      // outputs: 5.0
echo gettype($float); // outputs: double

These examples show that regardless of whether the input is an integer, string, boolean, or array, floatval can conveniently convert it to a floating‑point number.

It is important to note that if the variable cannot be converted to a float—such as a string containing non‑numeric characters—the function returns 0 . Therefore, you should ensure the variable’s type and value are appropriate before using the function.

In summary, PHP’s floatval function provides a quick and reliable way to cast variables to floats, which is especially useful in numerical calculations and financial processing.

backendPHPType Conversionphp-functionsfloatval
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.