简体   繁体   中英

How to calculate percentage within a value range in PHP

I have a value that i need to translate to a percentage given a certain set of rules.

VALUE=X

Where X can be anything starting from 0

If:

X > 200

the result of my function should be 100 (percent).

If:

X < 200 AND >= 100

the result should be between 100 and 50 (percent). Example: X=150 would be 75%

If:

X < 100 AND >= 80

the result should be between 50 and 25 (percent). Example: X=90 would be 37.5%

And if:

X < 80

the result should be between 25 and 0 (percent).

My approach in PHP would be something like

if($value > 200) return 100;
if($value > 100 && $value < 200) return ???;

... and so on.

Wherein ??? obviously stands for the formula i don't know how to set up.

Is there a way to do this in one single formula? And even if not - what is the mathematical approach to this problem?

I know it is very basic but it seems i skipped too many maths lessons in primary school.

The function can be defined piecewisely:

在此处输入图片说明

Graphically, this is represented with four straight lines of different gradients. While there isn't a way to represent this function without separate pieces, implementing the above is quite easy.

In PHP, this function can be written as:

function f($x) {
    if ($x >= 200)
        return 100;
    if ($x >= 100 && $x < 200)
        return 50 + 50 * (($x - 100) / 100);
    if ($x >= 80 && $x < 100)
        return 25 + 25 * (($x - 80) / 20);
    if ($x < 80)
        return 25 * ($x / 80);
}

First, determine which range you should be in. Then:

  • Subtract the bottom of the range.
  • Divide by the length of the range.
  • Multiply by the number of points difference over the range.
  • Add the number of points at the bottom of the range.

So X from 100 to 200 gives a score from 100 to 50. The bottom of the range is 100; the size of the range is 100 (200 - 100), and the score goes from 100 at the beginning to 50 at the end, so the difference is -50. Therefore -50 * ($value - 100) / 100 + 100 would work, or simplifying, -0.5 * ($value - 100) + 100 or 150 - $value * 0.5 .

Working another example, from 80 to 100: the bottom of the range is 80, the size of the range is 20, and the score goes from 25 to 50 (difference: -25). You get -25 * ($value - 80) / 20 + 25 , which simplifies to -1.25 * ($value - 80) + 25 or 125 - $value * 1.25

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