dtnbjjq51949 2015-01-16 14:46 采纳率: 0%
浏览 220
已采纳

如何检查数字(浮点数或整数)是否在一个范围内(0 - 100)

I'm looking for the fastest way to get this test. So functions, operands and everything else is allowed. I tried with the following regex (I'm not an expert):

0\.[0-9]+|100\.0+|100|[1-9]\d{0,1}\.{0,1}[0-9]+

It works except that it erroneously accept 0.0 or 0.000000 and so on. Also it's not the most appropriated and fastest way.

(if anybody wants to fix the regex to don't allow those 0.00 values it would be appreciated)`

  • 写回答

3条回答 默认 最新

  • drui0508 2015-01-16 14:54
    关注

    No need for regex:

    if (is_numeric($val) && $val > 0 && $val <= 100)
    {
        echo '$val is number (int or float) between 0 and 100';
    }
    

    Demo

    Update

    It turns out you're getting the numeric values from a string. In that case, it would be best to extract all of them using a regex, something like:

    if (preg_match_all('/\d+\.?\d*/', $string, $allNumbers))
    {
        $valid = [];
        foreach ($allNumbers[0] as $num)
        {
            if ($num > 0 && $num <= 100)
                $valid[] = $num;
        }
    }
    

    You can leave out the is_numeric check, because the matched strings are guaranteed to be numeric anyway...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog