php - 验证 PHP 中的 float 值

标签 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() 测试结合使用,但当我输入“1”时。 (注意数字后面的“。”)它应该捕获这个但显然不是。我不确定为什么是“1”。是 PHP 中有效的 float 变量。

最佳答案

因为 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 .

关于php - 验证 PHP 中的 float 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40019577/

相关文章:

php - 为什么 cURL 返回一个空字符串?

php - Laravel 中正确的命名空间

php - 保存检索到的数据

php - 什么?解析错误: syntax error, unexpected T_STRING in/file/path

javascript - $.getJSON 总是失败

php - Foreach - 递归?

php - Laravel welcome.blade.php 无法正确加载

php - 大图,保持右边内容的大小

php - 基于用户输入创建 mysqli 连接时是否必须净化提交表单数据?

php - 正则表达式 : how to capture the beginning, 一个模式和一行的结尾?