简体   繁体   中英

How to check if a number (float or integer) is within a range (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)`

Use bccomp

This is a perfect use case for BCMath functions.

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

From the manual:

Returns 0 if the two operands are equal, 1 if the left_operand is larger than the right_operand, -1 otherwise.

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

I think your regex pattern should look like this:

^\d{1,2}$|(100)

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM