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.
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
}
Just write
$count = number_format($count2, 2);
instead of
$count = number_format($count2, 0);
While keeping the rest of your code the same.
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.