PHP计算两个数字之间的百分比差异

时间:2018-11-01 07:50:21

标签: php

我试图找到两个数字的百分比差异。实际情况是iam获取本周和上周的用户数据总值。现在,我需要查看本周数据和上周数据的性能差异百分比。以下是我正在尝试的代码。但是有时任何一个数据都将为零,并且会出现错误“被零除”。如何处理?

$this_week_cust=$row["cust_count_new"];
$last_week_cust=$row["cust_count_old"];

$percentChange = (1 - $last_week_cust / $this_week_cust) * 100;

4 个答案:

答案 0 :(得分:1)

您可以检查$this_week_cust是否为零,只需将更改设置为100%

$this_week_cust=$row["cust_count_new"];
$last_week_cust=$row["cust_count_old"];
if ( $this_week_cust == 0 ) {
   $percentChange = -100;
}
else {
   $percentChange = (1 - $last_week_cust / $this_week_cust) * 100;
}

如果$last_week_cust也为0,那么更改将为0,所以也许

if ( $this_week_cust == 0 ) {
   $percentChange = ($last_week_cust==0)?0:-100;
}

答案 1 :(得分:0)

尝试

如果$this_week_cust!=0仅执行该时间计算,否则将不执行任何操作

$this_week_cust=$row["cust_count_new"];
$last_week_cust=$row["cust_count_old"];
if($this_week_cust!=0){
   $percentChange = (1 - $last_week_cust / $this_week_cust) * 100;
}

答案 2 :(得分:0)

您可以通过检查$this_week_cust来获得所需的结果,如果它返回零,为null或为空,则将$ this_week_cust设置为100;

$percentChange=100;

答案 3 :(得分:0)

我认为这会对您有所帮助。

$original= 1000;
$current = 5;
$diff = $current - $original;
$more_less = $diff > 0 ? "More" : "Less";
$diff = abs($diff);
$percentChange = ($diff/$original)*100;
echo "$percentChange% $more_less agaist $original";