Backend Development 4 min read

Using PHP's floatval Function to Convert Variables to Float

This article explains PHP’s built‑in `floatval` function, showing its syntax, how it converts various variable types—including integers, strings, booleans, and arrays—to floating‑point numbers, and highlights important considerations such as handling non‑numeric strings that result in a zero value.

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

In PHP we often need to convert variables to floating‑point numbers, which is useful for numeric calculations, monetary transactions, and similar tasks. PHP provides a built‑in function called floatval that can quickly convert a variable to a float.

The syntax of the floatval function is as follows:

floatval ( mixed $var ) : float

The function accepts one parameter $var , which can be any PHP variable such as an integer, string, etc. It attempts to convert the variable to a float and returns the resulting value.

Below are some example code snippets demonstrating how to use the floatval function to convert variables to floats.

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

From the examples it can be seen that whether the input is an integer, string, boolean, or array, the floatval function can conveniently convert it to a float.

Note that if a variable cannot be converted to a float, for example a string containing non‑numeric characters, floatval returns 0. Therefore you should ensure the variable’s type and value are as expected before using the function.

In summary, PHP’s floatval function helps quickly convert variables to floats. It is very useful for numeric calculations, monetary transactions, and similar scenarios. This article aims to help readers better understand and apply the floatval function.

backendPHPType Conversionnumericfloatval
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.