Reputation: 9008
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
Upvotes: 6
Views: 11556
Reputation: 1
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;
}
Upvotes: -1
Reputation: 5739
maybe 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;
}
Upvotes: 2
Reputation: 147
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.
Upvotes: 5
Reputation: 305
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().
Upvotes: 4