What is the easiest way to check if a string contains a valid float?
For example
is_string_float("1") = true
is_string_float("1.234") = true
is_string_float("1.2e3") = true
is_string_float("1b2") = false
is_string_float("aldhjsfb") = false
If you really want to know if a string contains a float and ONLY a float you cannot use is_float() (wrong type) or is_numeric() (returns true for a string like "1" too) only. I'd use
<?php
function foo(string $string) : bool {
return is_numeric($string) && strpos($string, '.') !== false;
}
?>
instead.
is_float() is checking the type not whether the value can be coerced to a float - which is what something like is_numeric() does but for integers.The easiest way would be to use built in function is_float(). To test if a variable is a number or a numeric string you must use is_numeric().
is_numeric is what I was looking formaybe you can use a couple of functions
out of the box
function is_string_float($string) {
if(is_numeric($string)) {
$val = $string+0;
return is_float($val);
}
return false;
}
echo "Z" + 0, "\n";. echo "1" + 0, "\n"; will print 1 without throwing any exception.This can easily be achieved by double casting.
/**
* @param string $text
* @return bool
*/
function is_string_float(string $text): bool
{
return $text === (string) (float) $text;
}
is_float("1") = false1in an integer"1"is a string, not a float. The same holds foris_float("1.234")