anderlaini
anderlaini

Reputation: 1821

php - how to calculate percentage with scale different from 0-100?

I want to check how percent is $current on the scale from $minimum to $maximum

$minimum = 0.5
$maximum = 5.5

$current = 2.5

How can I do that in PHP?

Upvotes: 0

Views: 299

Answers (1)

Paddy
Paddy

Reputation: 54

You would do that in PHP the same way you would do it in any other language or even if you write that calculation by hand.

Because minimum can be > 0 in your case, we subtract minimum from all values to make it easier in calculation. There's probably a faster way to do the maths behind that, however thats an algebra level that I cannot do

public function getPercentageValue($maximum, $minimum, $value) {
    $tempMax = $maximum - $minimum;
    $tempValue = $value - $minimum;

    return $tempValue / $tempMax;
}

Now if we take your values into consideration when we call getPercentageValue() we will get an answer of 0,4

$result = getPercentageValue(5.5, 0.5, 2.5);
echo $result; // 0.4

If you want the value not as float but as 40 for 40% you would change the function so that it multiplies the answer by 100

public function getPercentageValue($maximum, $minimum, $value) {
    $tempMax = $maximum - $minimum;
    $tempValue = $value - $minimum;

    return ($tempValue / $tempMax) * 100;
}

Upvotes: 1

Related Questions