处理 PHP 中的百分比

Dealing with percentages in PHP

我有一个百分比逻辑问题,我不太明白如何处理它。分享给大家:

我接到了一个任务,在某个时候我需要检查一些养老金收入(我认为它的价值)是否低于当前收入的 70%。如果是这样设置一个标志。都好。问题是我收到了一个测试应该是什么样子的例子:

Given my income on my pension is <percentage>% of my current
Then the status should be <status>

Example:
|percentage| status |
|100       | true   |
|71        | true   |
|68        | false  |
|20        | false  |

我创建了一个函数来查找这个百分比,因为其他方法不知道如何获取它,只有在测试中才动态给出值:

public function findPensionIncomePercentageFromTheCurrent()
{
    $pensionIncome = $this->getPensionIncome();

    $totalCurrentIncome = $this->getTotalCurrentIncome();

    if ($pensionIncome !== 0 && $totalCurrentIncome !== 0) {
        $percentage =  (int) round(($pensionIncome/$totalCurrentIncome) * 100, 0);

        return $percentage;
    }

    return false;
}

好的,这就是百分比。我还创建了另一个函数来计算当前收入的 70%。最后,我尝试将上述函数的百分比与 70% 的养老金收入的值进行比较。但我意识到只有当我再次将百分比乘以当前收入时才会起作用,例如:

$currentIncome = $this->getTotalCurrentIncome();

percentageOfCurrentIncome = 70% * $currentIncome;

$result = $this->findPensionIncomePercentageFromTheCurrent() * $currentIncome;

if ($result < percentageOfCurrentIncome)
    $this->setTrue(true);
else {
    $this->setFalse(false);

你觉得我的做法可以吗?我问是因为我发现通过 a/b * 100 找到百分比有点奇怪,然后将该百分比再次乘以 b 以获得结果。我认为我做得不好。

有什么建议吗?

从技术上讲,百分比是与比例相对应的数字。

因此,如果您的收入为 1000,养老金为 300,那么养老金占收入的百分比在数值上为 0.3,而不是 30%。

这是你应该做的:

public function findPensionIncomePercentageFromTheCurrent()
{
    $pensionIncome = $this->getPensionIncome();

    $totalCurrentIncome = $this->getTotalCurrentIncome();

    if ($pensionIncome !== 0 && $totalCurrentIncome !== 0) {
        $percentage =  ($pensionIncome/$totalCurrentIncome);

        return $percentage;
    }

    return false;
}

那么就是:

 $currentIncome = $this->getTotalCurrentIncome();

 //0.7 is the real percentage value, 
 //70% is just something people use because we like whole numbers more
 $threshold = 0.7 * $currentIncome; 

 $result = $this->findPensionIncomePercentageFromTheCurrent() * $currentIncome;

 if ($result < $threshold)
   $this->setTrue(true);
 else {
   $this->setFalse(false);

现在需要注意的是,如果您需要向需要执行以下操作的人显示百分比:

echo round($percentage*100). "%"; //Would print something like 70%