Reputation: 9191
I started learning PHP to do some pet project, and I am trying to get this around my head on how to validate a valid float or double in PHP
Supposed I have this code in HTML that ask for interest rate
<input type="text" name="interest" size="5" >
In My PHP code, I wanted to validate if this is a valid interest rate:
<?php
$interest = $_POST['interest']
//isset - empty test (not- shown)
if(!is_numeric($interest) && is_float($interest)){
print "<p><span class='error'>Interest should be numeric</span></p>";
}
?>
I have my is_numeric() test first then I coupled it with the is_float() test but when I enter "1." (note the "." after the number) it should catch this but apparently not. I am not sure why "1." is a valid floating variable in PHP.
Upvotes: 2
Views: 4542
Reputation: 95
Use PHP built-in function
filter_var("your float", FILTER_VALIDATE_FLOAT)
Upvotes: 2
Reputation: 723
i know this is too late. but solution i implemented:
function isFloat($floatString)
{
return (bool)preg_match('/(^\d+\.\d+$|^\d+$)/',$floatString);
}
Upvotes: 1
Reputation: 7911
I have had a question why PHP picks up the 1.
as a float as well, check out this question for more information.
There might be 1 reason why the code is failing, and that is because a any data retrieved from the http header (post, get, cookie) is a string type.
is_float()
checks the type, not the content of the variable where is_numeric()
only checks the value. However, you can try to convert the value by doing the following:
$interest = $_POST['interest'];
if(isset($interest)){
if(is_numeric($interest) && !is_float($interest + 0)){
echo "$interest is a integer";
} else {
echo "$interest is not an integer";
}
} else {
echo 'Value not posted';
}
If the value of $interest
is a float, it stays a float. If it is a string that cannot be parsed as a float, it will convert it to 0, in which is_float()
will return false because it is not a float. In short, now it will only except integer values.
You could also use the filter_var()
method explained in deceze's post.
Upvotes: 1
Reputation: 1584
Another option
if( strpos( $interest, '.' ) )
{
print "<p><span class='error'>Interest should be numeric</span></p>";
}
Upvotes: -1
Reputation: 522016
Since POST or GET data will always be a string, is_float
will always be false
. The easiest way to deal with that is to use methods specifically designed for it:
$interest = filter_input(INPUT_POST, 'interest', FILTER_VALIDATE_FLOAT);
if (!$interest) { // take care here if you expect 0 to be valid
print 'Nope';
}
See http://php.net/filter_input.
Upvotes: 3