我需要帮助。这是一段简单的代码,但我不知道该如何写下来。我有以下数字:
$NumberOne = 500;
$NumberTwo = 430;
$NumberThree = 150;
$NumberFour = 30;
总之,这就是:
$Everything = 1110; // all added
现在我想展示例如$NumberFour在总数中占多少百分比,或者$NumberTwo在$Everything中占多少百分比。这就是"市场份额"。
我需要帮助。这是一段简单的代码,但我不知道该如何写下来。我有以下数字:
$NumberOne = 500;
$NumberTwo = 430;
$NumberThree = 150;
$NumberFour = 30;
总之,这就是:
$Everything = 1110; // all added
使用简单的数学公式:将您要找到百分比的数字除以总数,然后乘以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/zh/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
/**
* Calculate percetage between the numbers
*/
function percentageOf( $number, $everything, $decimals = 2 ){
return round( $number / $everything * 100, $decimals );
}
$numbers = array( 500, 430, 150, 30 );
$everything = array_sum( $numbers );
echo 'First of everything: '.percentageOf( $numbers[0], $everything )."%\n";
echo 'Second of everything: '.percentageOf( $numbers[1], $everything )."%\n";
echo 'Third of everything: '.percentageOf( $numbers[2], $everything )."%\n";
echo 'Fourth of everything: '.percentageOf( $numbers[3], $everything )."%\n";
?>
First of everything: 45.05%
Second of everything: 38.74%
Third of everything: 13.51%
Fourth of everything: 2.7%
(部分/总数) * 100
。 - jnovacho