开发者

Negative & Positive Percentage Calculation

Let's say i have 3 sets of numbers and i want the % o开发者_开发问答f their difference.

30 - 60
94 - 67
10 - 14

I want a function that calculate the percentage of the difference between each 2 numbers, and the most important is to support positive and negative percentages.

Example:

30 - 60 : +100%
94 - 67 : -36% ( just guessing )
10 - 14 : +40%

Thanks


This is pretty basic math.

% difference from x to y is 100*(y-x)/x


The important issue here is whether one of your numbers is a known reference, for example, a theoretical value.

With no reference number, use the percent difference as

100*(y-x)/((x+y)/2)

The important distinction here is dividing by the average, which symmetrizes the definition.

From your example though, it seems that you might want percent error, that is, you are thinking of your first number as the reference number and want to know how the other deviates from that. Then the equation, where x is reference number, is:

100*(y-x)/x

See, e.g., wikipedia, for a small discussion on this.


for x - y the percentage is (y-x)/x*100


Simple math:

function differenceAsPercent($number1, $number2) {
    return number_format(($number2 - $number1) / $number1 * 100, 2);
}

    echo differenceAsPercent(30, 60); // 100
    echo differenceAsPercent(94, 67); // -28.72
    echo differenceAsPercent(10, 14); // 40


If the percentage is needed for a voting system then Andrey Korolyov is the only who answered correctly.

Example

10 votes for 1 vote against = 90%
10 votes for 5 votes against = 50%
10 votes for 3 votes against = 70%
100 votes for 1 vote against = 99%
1000 votes for 1 vote against = 99.9%

1 votes for 10 vote against = -90%
5 votes for 10 votes against = -50%
3 votes for 10 votes against = -70%
1 votes for 100 vote against = -99%
1 votes for 1000 vote against = -99.9%

function perc(a,b){
console.log( (a > b) ? (a-b)/a*100 : (b - a)/b*-100);

}


$c = ($a > $b) ? ($a-$b)/$a*-100 : ($b-$a)/$b*100;  

In Ukraine children learn these math calculations at the age of 12 :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜