验证PHP中的浮点值

时间:2016-10-13 11:21:01

标签: php

我开始学习PHP来做一些宠物项目,我试图让我了解如何在PHP中验证有效的float或double

假设我有这个HTML代码要求利率

<input type="text" name="interest" size="5" >

在我的PHP代码中,我想验证这是否是有效的利率:

<?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>";
    }
?>

我首先进行is_numeric()测试,然后将其与is_float()测试结合,但是当我输入&#34; 1。&#34; (注意&#34;。&#34;在数字之后)它应该抓住这个但显然不是。我不确定为什么&#34; 1。&#34;是PHP中的有效浮点变量。

6 个答案:

答案 0 :(得分:3)

由于POST或GET数据始终为字符串,is_float始终为false。最简单的方法是使用专门为它设计的方法:

$interest = filter_input(INPUT_POST, 'interest', FILTER_VALIDATE_FLOAT);
if (!$interest) {  // take care here if you expect 0 to be valid
    print 'Nope';
}

请参阅http://php.net/filter_input

答案 1 :(得分:1)

我有一个问题,为什么PHP也会将1.作为浮点数获取,请查看this question以获取更多信息。

代码失败可能有一个原因,那是因为从http标头(post,get,cookie)检索的任何数据都是字符串类型。

is_float()检查类型,而不是is_numeric()仅检查值的变量的内容。但是,您可以尝试通过执行以下操作来转换值:

$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';
}

如果$interest的值是浮点数,则它保持浮点数。如果它是一个无法解析为float的字符串,它会将其转换为0,其中is_float()将返回false,因为它不是float。简而言之,现在它只会出现整数值。

您还可以使用deceze's帖子中解释的filter_var()方法。

答案 2 :(得分:0)

最好将输入标记定义为数字

<input type="number" name="interest" size="5" >

你可以用php查看它是否是一个数字

foreach ($interest as $element) {
    if (is_numeric($element)) {
        echo "'{$element}' is numeric", PHP_EOL;
    } else {
        echo "'{$element}' is NOT numeric", PHP_EOL;
    }
}

来源:http://php.net/manual/en/function.is-numeric.php

答案 3 :(得分:0)

我知道这为时已晚。 但是我实施了解决方案:

function isFloat($floatString)
{
   return (bool)preg_match('/(^\d+\.\d+$|^\d+$)/',$floatString);
}

答案 4 :(得分:0)

使用 PHP 内置函数

filter_var("your float", FILTER_VALIDATE_FLOAT)

答案 5 :(得分:-1)

另一个选择

if( strpos( $interest, '.' ) )
{
    print "<p><span class='error'>Interest should be numeric</span></p>";
}