【问题标题】:Calculate percentage increase between two decimal numbers计算两个小数之间的百分比增加
【发布时间】:2011-09-06 15:32:47
【问题描述】:

我有一些十进制数字存储在数据库中,需要使用 PHP 计算两个数字之间的百分比增加(或减少)。

其中两个数字的示例是:111.0516 和 111.9052,这将增加 0.7628%

我在某处找到了以下代码。不幸的是,它似乎不适用于十进制数字并将它们四舍五入:

$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);

理想情况下,我需要计算百分比到小数点后两位,给出 0.77% 的答案。

这可以通过 PHP 实现吗?我难住了。我的 PHP 或数学技能都不够好,无法弄清楚。

【问题讨论】:

    标签: php math


    【解决方案1】:

    让我们做一些数学运算。

    如果你有 4 欧元,我给你 2 欧元,你有 6 欧元,增加 2 / 6。

    如果你有x欧元,我给你delta欧元,你就有x + delta = y欧元

    我们可以写

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

    所以你的函数变成了:

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

    Codepad example

    【讨论】:

    • 如果它是完美的,为什么不将其标记为正确答案?将帮助无法重复您的问题的我们将完美标记为:完美!
    • 这是什么意思 1 - ( 1 - $num_amount / $num_total)?你能给我原来的公式吗?
    【解决方案2】:

    随便写

    $count = number_format($count2, 2);
    

    而不是

    $count = number_format($count2, 0);
    

    同时保持其余代码相同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-11
      • 2011-08-13
      • 2021-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多