gpt4 book ai didi

PHP计算百分比

转载 作者:行者123 更新时间:2023-12-03 22:44:53 26 4
gpt4 key购买 nike

我需要帮助。这是一个简单的代码,但我不知道如何写下来。我有数字:

$NumberOne = 500;
$NumberTwo = 430;
$NumberThree = 150;
$NumberFour = 30;

这就是:
$Everything = 1110; // all added

现在我想显示什么百分比是例如 $NumberFour 的所有内容或 $NumberTwo 的 $Everything 百分比。所以是“市场份额”。

最佳答案

使用一些简单的数学方法:将要计算百分比的数字除以总数,然后乘以 100。
例子:

$total = 250;
$portion = 50;
$percentage = ($portion / $total) * 100; // 20
原始示例的解决方案
获取 $NumberFour作为您使用的总金额的百分比:
$percentage = ($NumberFour / $Everything) * 100;
四舍五入
根据您使用的数字,您可能希望对结果百分比进行四舍五入。在我最初的例子中,我们得到 20%,这是一个很好的整数。然而,原始问题使用 1110 作为总数和 30 作为数字来计算 (2.70270...) 的百分比。
PHP 内置 round()使用百分比显示时,函数可能很有用: https://www.php.net/manual/en/function.round.php
echo round($percentage, 2) . '%'; // 2.7% -- (30 / 1110) * 100 rounded to 2dp
辅助函数
我只会考虑在它们的使用证明其合理时创建辅助函数(如果计算和显示百分比不是一次性的)。我在下面附上了一个例子,将上面的所有内容联系在一起。
function format_percentage($percentage, $precision = 2) {
return round($percentage, $precision) . '%';
}

function calculate_percentage($number, $total) {

// Can't divide by zero so let's catch that early.
if ($total == 0) {
return 0;
}

return ($number / $total) * 100;
}

function calculate_percentage_for_display($number, $total) {
return format_percentage(calculate_percentage($number, $total));
}

echo calculate_percentage_for_display(50, 250); // 20%
echo calculate_percentage_for_display(30, 1110); // 2.7%
echo calculate_percentage_for_display(75, 190); // 39.47%

关于PHP计算百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29181711/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com