0

I need to (check) if my input is float but I cannot get it to work.

    $input_number = trim($_POST['number']);
    if(empty($input_number)){
        $input_number_err = 'an error msg';
    } elseif(is_float($input_number)){
        $number = $input_number;
    } else{
        $input_number_err = 'an error msg';
    }

I also tried to add 0 inside my if statement but nothing changed

elseif(is_float($input_number + 0))
4
  • The input values I am providing (10.50 , 10.5) . Both dont work Commented Apr 16, 2021 at 23:26
  • When you say it doesn't work, what does that mean? At no point in the above code do you output anything to see if it worked? (and this would work with +0) Commented Apr 16, 2021 at 23:29
  • I mean that it doesnt rerurn true as it should. I know that +0 should work but it doesnt in the code I posted. Commented Apr 16, 2021 at 23:46
  • The above code definitely does work with +0 (assuming that your $_POST["number"] is a string); you should var_dump your $_POST and see what that actually shows Commented Apr 17, 2021 at 0:05

1 Answer 1

1

You should make use of floatval() here, to convert your string to a float, if possible.

As an example:

$input_number = trim($_POST['number']);
if (empty($input_number)) {
  $input_number_err = 'an error msg';
}
elseif (floatval($input_number)) {
  $number = $input_number;
}
else {
  $input_number_err = 'an error msg';
}

// Feedback
if (isset($number)) {
  echo 'Your float is: ' . $number;
}
elseif (isset($input_number_err)) {
  echo 'Your input is not a float: ' . $input_number_err;
}
Sign up to request clarification or add additional context in comments.

1 Comment

floatval isn't the best solution here because it will cause unexpected behaviour in some situations (e.g. floatval("randomString") === 0.0); also 0.0 == false but potentially is a valid input? It seems is_numeric would be the better choice

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.