PHP计算百分比

时间:2015-03-21 10:36:09

标签: php percentage

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

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

这就是:

$Everything = 1110; // all added

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

2 个答案:

答案 0 :(得分:9)

使用一些基本数学。

要获得$NumberFour占您使用总金额的百分比:

$percentage = ( $NumberFour / $Everything ) * 100;

答案 1 :(得分:4)

创建函数来计算两个数字之间的百分比。

<?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%