Backend Development 4 min read

Using PHP floatval() to Convert Variables to Float

This article explains PHP's built-in floatval() function, its syntax, and provides multiple code examples showing how to convert integers, strings, booleans, and arrays to floating-point numbers, while also noting its behavior when conversion is not possible.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP floatval() to Convert Variables to Float

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

The floatval function syntax is as follows:

floatval ( mixed $var ) : float

This 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 result.

Below are example codes demonstrating how to use the floatval function to convert variables to float.

// Convert an integer to float
$int = 10;
$float = floatval($int);
echo $float;          // outputs: 10.0
echo gettype($float); // outputs: double

// Convert a 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 to float
$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 to float (the first element is used)
$arr = [5, 10, 15];
$float = floatval($arr);
echo $float;          // outputs: 5.0
echo gettype($float); // outputs: double

From the examples, we can see that regardless of whether the input is an integer, string, boolean, or array, floatval conveniently converts it to a float.

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

In summary, the PHP floatval function helps quickly convert variables to floating‑point numbers. It is especially useful in numeric calculations and monetary transactions, and understanding its behavior enables developers to use it effectively.

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.