kuus
kuus

Reputation: 500

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)`

Upvotes: 0

Views: 6293

Answers (3)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76395

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

Upvotes: 3

Tek
Tek

Reputation: 3050

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.

Upvotes: 4

violator667
violator667

Reputation: 499

I think your regex pattern should look like this:

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

Demo

Upvotes: 0

Related Questions