如何检查数字(浮点数或整数)是否在范围内(0 - 100)
How to check if a number (float or integer) is within a range (0 - 100)
我正在寻找获得此测试的最快方法。
所以 functions
、operands
和其他一切都是允许的。
我尝试了以下 regex
(我不是专家):
0\.[0-9]+|100\.0+|100|[1-9]\d{0,1}\.{0,1}[0-9]+
除了错误地接受 0.0
或 0.000000
等,它有效。
另外这不是最合适和最快的方式。
(如果有人想修复正则表达式以不允许那些 0.00
值,我们将不胜感激)`
不需要正则表达式:
if (is_numeric($val) && $val > 0 && $val <= 100)
{
echo '$val is number (int or float) between 0 and 100';
}
Demo
更新
事实证明,您是从字符串中获取数值。在这种情况下,最好使用正则表达式提取所有这些,例如:
if (preg_match_all('/\d+\.?\d*/', $string, $allNumbers))
{
$valid = [];
foreach ($allNumbers[0] as $num)
{
if ($num > 0 && $num <= 100)
$valid[] = $num;
}
}
您可以省略 is_numeric
检查,因为无论如何匹配的字符串都保证是数字...
我认为你的 regex
模式应该是这样的:
^\d{1,2}$|(100)
使用bccomp
这是 BCMath 函数的完美用例。
function compare_numberic_strings($number) {
if (
is_numeric($number) &&
bccomp($number, '0') === 1 &&
bccomp($number, '100') === -1
) {
return true;
}
return false;
}
echo compare_numberic_strings('0.00001');
//returns true
echo compare_numberic_strings('50');
//returns true
echo compare_numeric_strings('100.1');
//returns false
echo compare_numeric_strings('-0.1');
//returns false
来自手册:
Returns 0 if the two operands are equal, 1 if the left_operand is
larger than the right_operand, -1 otherwise.
我正在寻找获得此测试的最快方法。
所以 functions
、operands
和其他一切都是允许的。
我尝试了以下 regex
(我不是专家):
0\.[0-9]+|100\.0+|100|[1-9]\d{0,1}\.{0,1}[0-9]+
除了错误地接受 0.0
或 0.000000
等,它有效。
另外这不是最合适和最快的方式。
(如果有人想修复正则表达式以不允许那些 0.00
值,我们将不胜感激)`
不需要正则表达式:
if (is_numeric($val) && $val > 0 && $val <= 100)
{
echo '$val is number (int or float) between 0 and 100';
}
Demo
更新
事实证明,您是从字符串中获取数值。在这种情况下,最好使用正则表达式提取所有这些,例如:
if (preg_match_all('/\d+\.?\d*/', $string, $allNumbers))
{
$valid = [];
foreach ($allNumbers[0] as $num)
{
if ($num > 0 && $num <= 100)
$valid[] = $num;
}
}
您可以省略 is_numeric
检查,因为无论如何匹配的字符串都保证是数字...
我认为你的 regex
模式应该是这样的:
^\d{1,2}$|(100)
使用bccomp
这是 BCMath 函数的完美用例。
function compare_numberic_strings($number) {
if (
is_numeric($number) &&
bccomp($number, '0') === 1 &&
bccomp($number, '100') === -1
) {
return true;
}
return false;
}
echo compare_numberic_strings('0.00001');
//returns true
echo compare_numberic_strings('50');
//returns true
echo compare_numeric_strings('100.1');
//returns false
echo compare_numeric_strings('-0.1');
//returns false
来自手册:
Returns 0 if the two operands are equal, 1 if the left_operand is larger than the right_operand, -1 otherwise.