Calculate percentage saved between two numbers?

前端 未结 9 1595
自闭症患者
自闭症患者 2020-12-22 19:25

I have two numbers, the first, is the original price, the second, is the discounted price.

I need to work out what percentage a user saves if they

9条回答
  •  悲&欢浪女
    2020-12-22 19:44

    I see that this is a very old question, but this is how I calculate the percentage difference between 2 numbers:

    (1 - (oldNumber / newNumber)) * 100
    

    So, the percentage difference from 30 to 40 is:

    (1 - (30/40)) * 100 = +25% (meaning, increase by 25%)
    

    The percentage difference from 40 to 30 is:

    (1 - (40/30)) * 100 = -33.33% (meaning, decrease by 33%)
    

    In php, I use a function like this:

    function calculatePercentage($oldFigure, $newFigure) {
            if (($oldFigure != 0) && ($newFigure != 0)) {
                $percentChange = (1 - $oldFigure / $newFigure) * 100;
            }
            else {
                $percentChange = null;
            }
            return $percentChange;
    }
    

提交回复
热议问题