6

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
3
  • because that's not what I'm looking for. is_float("1") = false Commented Dec 5, 2016 at 11:54
  • 2
    False because 1 in an integer Commented Dec 5, 2016 at 11:54
  • no, because "1" is a string, not a float. The same holds for is_float("1.234") Commented Dec 5, 2016 at 11:56

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
4

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().

1 Comment

is_numeric is what I was looking for
3

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;
}

3 Comments

This will error in PHP8 as addition cannot be performed on a string and an int.
@Harry I'm pretty sure the is_numeric check would ensure that PHP treats the string as an int (or float) before the addition operation is done.
PHP 8.2 complains only with code similar to echo "Z" + 0, "\n";. echo "1" + 0, "\n"; will print 1 without throwing any exception.
-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;
}

1 Comment

Unfortunately, this does not work on a string like "0.000"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.