-1

I am using is_float() to check if the number entered is float or not but it keeps throwing the echo() message when I enter 3.00. Is there any other solution to it? Or am I doing anything wrong?

Here is my code:

PHP:

if(!is_float($_POST["gpa"])){
    echo "GPA must be in #.## format.";
}

HTML:

<input type="text" name="gpa" />
user4244510
  • 79
  • 1
  • 8
  • possible duplicate of [is\_int, is\_numeric, is\_float, and HTML form validation](http://stackoverflow.com/questions/5486926/is-int-is-numeric-is-float-and-html-form-validation) – leo Feb 02 '15 at 20:20
  • Works fine for me! Please show us your input, current output and your expected output – Rizier123 Feb 02 '15 at 20:21
  • 3.00 is my input @Rizier123 – user4244510 Feb 02 '15 at 20:21
  • 2
    The input is always a string or array (if specified), so `is_float` will always return false and therefor the if condition is true. Use `filter_var()` with `FILTER_VALIDATE_FLOAT` instead. – Charlotte Dunois Feb 02 '15 at 20:25
  • are you sure there are no excess characters, like spaces around? Try `trim()`-ming the value prior to its usage – Oleg Dubas Feb 02 '15 at 20:25

4 Answers4

5

Form inputs are always a string, so the if condition will always return the error message you specified. Make use of filter_var() instead.

if(filter_var($_POST['gpa'], FILTER_VALIDATE_FLOAT) === false) {
    echo "GPA must be in #.## format.";
}

If you want to validate the format you need to use Regular Expressions.

([0-9]{1,})\.([0-9]{2,2})

You could use RegEx alone and forget about filter_var(), since it does the same.

if(preg_match('/([0-9]{1,})\.([0-9]{2,2})/', $_POST['gpa']) == 0) {
    echo "GPA must be in #.## format.";
}
Charlotte Dunois
  • 4,638
  • 2
  • 20
  • 39
4

try this :

$num = 2.6;

if($num === floatval($num)){
    echo 'is float';
}else{
    echo 'is not';
}

other way is regex:

$num = '345.56678';//post is string

$patt = '/^\d+\.{1}\d+$/';
$resp = preg_match($patt,$num);
if($resp){
    echo 'is float';
}else{
    echo 'is not';
}
miglio
  • 2,048
  • 10
  • 23
  • Will I have to use reggae to limit the entry to #.## format? – user4244510 Feb 02 '15 at 20:35
  • floatval is not working for me for some reason but this does: `if($num == (float)$num)(echo 'is float';)` - it will not filter `int` thou (but you can create another if using the same trick and `(int)$num` ) – baron_bartek Apr 24 '18 at 07:50
2

From the documentation

Finds whether the type of the given variable is float.

To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric().

By definition, your $_POST["gpa"] is a string, not a float. You can see this when you do var_dump($_POST["gpa"])

Community
  • 1
  • 1
Machavity
  • 30,841
  • 27
  • 92
  • 100
2

The correct way to validate the float value in a string will be:

if( !filter_var($_POST["gpa"], FILTER_VALIDATE_FLOAT) ) echo 'error!';
Oleg Dubas
  • 2,320
  • 1
  • 10
  • 24