I am trying to check in php if a string is a double or not.
Here is my code:
if(floatval($num)){
$this->print_half_star();
}
$num is a string..The problem is that even when there is an int it gives true. Is there a way to check if it is a float and not an int!?
// Try to convert the string to a float
$floatVal = floatval($num);
// If the parsing succeeded and the value is not equivalent to an int
if($floatVal && intval($floatVal) != $floatVal)
{
// $num is a float
}
This will omit integer values represented as strings:
if(is_numeric($num) && strpos($num, ".") !== false)
{
$this->print_half_star();
}
You can try this:
function isfloat($num) {
return is_float($num) || is_numeric($num) && ((float) $num != (int) $num);
}
var_dump(isfloat(10)); // bool(false)
var_dump(isfloat(10.5)); // bool(true)
var_dump(isfloat("10")); // bool(false)
var_dump(isfloat("10.5")); // bool(true)
You could just check if the value is numeric, and then check for a decimal point, so...
if(is_numeric($val) && stripos($val,'.') !== false)
{
//definitely a float
}
It doesn't handle scientific notation very well though, so you may have to handle that manually by looking for e
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With