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.
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.
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.
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.
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
Just write
$count = number_format($count2, 2);
instead of
$count = number_format($count2, 0);
While keeping the rest of your code the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With