note 117304 added to function.is-float
| From: | Erutan409 at Hotmail dot com | Date: | Tue, 19 May 2015 14:37:29 +0000 |
| Subject: | note 117304 added to function.is-float | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-202607@lists.php.net to get a copy of this message | ||
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.
----
Server IP: 72.52.91.14
Probable Submitter: 74.204.21.6
----
Manual Page -- http://php.net/manual/en/function.is-float.php
Edit -- https://master.php.net/note/edit/117304
Del: integrated -- https://master.php.net/note/delete/117304/integrated
Del: useless -- https://master.php.net/note/delete/117304/useless
Del: bad code -- https://master.php.net/note/delete/117304/bad+code
Del: spam -- https://master.php.net/note/delete/117304/spam
Del: non-english -- https://master.php.net/note/delete/117304/non-english
Del: in docs -- https://master.php.net/note/delete/117304/in+docs
Del: other reasons-- https://master.php.net/note/delete/117304
Reject -- https://master.php.net/note/reject/117304
Search -- https://master.php.net/manage/user-notes.php