Skip to content
Advertisement

PHP is_float() validation

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

Advertisement

Answer

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;
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement