PHP 8.5.0 Alpha 1 available for testing

Voting

: nine plus zero?
(Example: nine)

The Note You're Voting On

Erutan409 at Hotmail dot com
10 years ago
Boylett's solution is elegant (http://php.net/manual/en/function.is-float.php#85848), but won't work for long float's or variables that are not explicitly type of 'string' or for long floats that are encased in quotes, making it a string that will be truncated/rounded when cast to a float. So, further logic must be completed to test for the case. Take the following example:

<?php

if (!function_exists("test_float")) {

function
test_float($test) {

if (!
is_scalar($test)) {return false;}

$type = gettype($test);

if (
$type === "float") {
return
true;
} else {
return
preg_match("/^\\d+\\.\\d+$/", $test) === 1;
}

}

}

$test = "3.14159265358979323846264338g32795";

var_dump($test);
var_dump((float)$test);
var_dump($test == (string)(float)$test);
var_dump(test_float($test));

?>

Will produce (32-bit):

string(34) "3.14159265358979323846264338g32795"
float(3.1415926535898)
bool(false)
bool(false)

So far, so good, right? Yeah, but it's misleading, because the string is so long, that when it's converted to a float, it won't be equivalent to the comparison of the value being cast back into a string . So the aforementioned short function works. Look at this next example:

<?php

$test
= 3.1415926535897932384626433832795;

var_dump($test);
var_dump((float)$test);
var_dump($test == (string)(float)$test);
var_dump(test_float($test));

?>

Will produce (32-bit):

float(3.1415926535898)
float(3.1415926535898)
bool(false)
bool(true)

Why is it not working now, but the value is truly a float? Same reasoning as mentioned before. The float is so long that it's truncated/rounded and doesn't match the comparison being done with the short-hand function.

So, as you can see, more logic should be applied to the variable you're testing.

<< Back to user notes page

To Top