marcosh
marcosh

Reputation: 9008

php - check if a string contains a float

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

Answers (4)

Joost Nijhuis
Joost Nijhuis

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

donald123
donald123

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

Lenny Eing
Lenny Eing

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

Marko Ivančić
Marko Ivančić

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

Related Questions