Floating numbers are numbers that have a decimal point.
$x = 1.5;
Similar to an integer, the size of a floating number depends on the platform.
We can check using these constants: PHP_FLOAT_MAX and PHP_FLOAT_MIN.
echo PHP_FLOAT_MAX; // 1.7976931348623E+308
You will get INF (is infinite) if you go out of the boundary.
To compare if a variable is infinite, we use a function is_infinite()
. The opposite is the function is_finite()
.
$x = PHP_FLOAT_MAX * 2;
var_dump($x); // float(INF)
var_dump(is_infinite($x)); // bool(true)
var_dump(is_finite($x)); // bool(false)
NAN stands for “Not A Number”.
We can use the function is_nan()
to check if an argument is not a number.
var_dump(log(-1)); // float(NAN)
var_dump(is_nan(log(-1))); // bool(true)
We can convert data types into a float by casting (float) before an argument.
$x = 1;
var_dump($x); // int(1)
var_dump((float) $x); // float(1)
Note: When converting a string into a float, if a string can be represented as a number, it can be converted into a float. Otherwise, it will be 0.
$x = "abc";
$y = "40.2a";
var_dump((float) $x); // float(0)
var_dump((float) $y); // float(40.2)