0

I have a number that comes as a string from an input. It could be "450.021" or "30". I need to determine whether it is int or a float number. How do I do that?

I tried with intval but apparently floating numbers are floored and in my case it is not going to help me.

blako
  • 33
  • 6

1 Answers1

0

Very naiv approach

    foreach(["342.23", "30"] as $a) {
        if( (float)(int)$a === (float)$a ) {
            echo "int";
        } else {
            echo "float";
        }
    }

But this won't catch cases where you parse "340.0".

Edit: Digging a bit more:

    foreach(["342.23", "30"] as $a) {
        $is_float = filter_var($a, FILTER_VALIDATE_FLOAT);
        $is_int = filter_var($a, FILTER_VALIDATE_INT);

        if( $is_float && $is_int ) {
            echo $a . " is Int";
        } else if( $is_float && !$is_int ) {
            echo $a . " is Float";
        }

    }
huehnerhose
  • 615
  • 9
  • 26