简体   繁体   中英

Percentage increase or decrease between two values

How do I calculate the percentage of increase or decrease of two numbers in PHP?

For example: (increase)100, (decrease)1 = -99% (increase)1, (decrease)100 = +99%

Before anything else you need to have a solid understanding of the meaning of percentages and how they are computed.

The meaning of " x is 15% of y " is:

x = (15 * y) / 100

The arithmetic operations with percentages are similar. If a increases with 12% (of its current value) then:

a = a + (12 * a) / 10

Which is the same as:

a = 112 * a / 100

Subtracting 9% (of its current value) from b is:

b = b - (9 * b) / 100

or

b = b * 91 / 100

which actually is 91% of the value of b ( 100% - 9% of b ).


Turn the above a , b , x , y into PHP variables (by placing $ in front of them), terminate the statements with semicolons ( ; ) and you get valid PHP code that performs percentage operations.

PHP doesn't provide any particular function that helps working with percentages. As you can see above, there is no need for them.

My 2 cents ;)

Using PHP

function pctDiff($x1, $x2) {
    $diff = ($x2 - $x1) / $x1;
    return round($diff * 100, 2);
}

Usage:

$oldValue = 1000;
$newValue = 203.5;
$diff = pctDiff($oldValue, $newValue);
echo pctDiff($oldValue, $newValue) . '%'; // -79.65%

Using Swift 3

func pctDiff(x1: CGFloat, x2: CGFloat) -> Double {
    let diff = (x2 - x1) / x1
    return Double(round(100 * (diff * 100)) / 100)
}

let oldValue: CGFloat = 1000
let newValue: CGFloat = 203.5
print("\(pctDiff(x1: oldValue, x2: newValue))%") // -79.65%

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