Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate percentage increase between two decimal numbers

Tags:

php

math

I have a number of decimal numbers stored in a database and need to calculate the percentage increase(or decrease) between two of the numbers using PHP.

An example of two of the numbers are: 111.0516 and 111.9052 which would be an increase of 0.7628%

I found the following code somewhere. Unfortunately it doesn't seem to work with decimal numbers and rounds them up:

$num_amount = 111.0516;
$num_total = 111.9052;

function percent($num_amount, $num_total) {
$count1 = $num_amount / $num_total;
$count2 = $count1 * 100;
$count = number_format($count2, 0);
echo $count;
}

percent($num_amount, $num_total);

Ideally I need to calculate the percentage to two decimal places giving an answer of 0.77%.

Is this possible with PHP? I'm stumped. Neither my PHP or maths skills are good enough to figure it out.

like image 845
Turnip Avatar asked Sep 06 '11 15:09

Turnip


People also ask

How do you work out a percentage increase from a decimal?

So 25% is 25/100, or 0.25. To convert a decimal to a percentage, multiply by 100 (just move the decimal point 2 places to the right). For example, 0.065 = 6.5% and 3.75 = 375%. To find a percentage of a number, say 30% of 40, just multiply.

How do you find the percent difference between two decimals?

Percentage Difference Formula The percentage difference between two values is calculated by dividing the absolute value of the difference between two numbers by the average of those two numbers. Multiplying the result by 100 will yield the solution in percent, rather than decimal form.

How do you calculate percentage increase?

Subtract the original value from the new value, then divide the result by the original value. Multiply the result by 100. The answer is the percent increase.


2 Answers

Let's do a bit of maths.

If you have 4 euros and i give ou 2 euros, you have 6 euros, the increase is 2 / 6.

If you have x euros and I give you delta euros, you have x + delta = y euros

We can write

percentage_increase := (delta / y) * 100
                    := ((y - x) / y) * 100
                    := (1 - (x / y)) * 100

So your function becomes:

function percent($num_amount, $num_total) {
    echo number_format((1 - $num_amount / $num_total) * 100, 2); // yields 0.76
}

Codepad example

like image 152
Benjamin Crouzier Avatar answered Sep 27 '22 19:09

Benjamin Crouzier


Just write

$count = number_format($count2, 2);

instead of

$count = number_format($count2, 0);

While keeping the rest of your code the same.

like image 33
AndreyKo Avatar answered Sep 27 '22 18:09

AndreyKo