php PHP计算百分比
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29181711/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP calculate percentages
提问by Chris
I need some help. It's a simple code, but I don't have idea how to write in down. I have the numbers:
我需要帮助。这是一个简单的代码,但我不知道如何写下来。我有数字:
$NumberOne = 500;
$NumberTwo = 430;
$NumberThree = 150;
$NumberFour = 30;
At all this is:
这一切是:
$Everything = 1110; // all added
Now I want to show what percentage is for example $NumberFour of everything or what percentage is $NumberTwo of $Everything. So the "market share".
现在我想显示什么百分比是例如 $NumberFour 的所有内容或 $NumberTwo 的 $Everything 百分比。所以是“市场份额”。
回答by Nathan Dawson
Use some basic maths.
使用一些基本的数学。
To get $NumberFour
as the percentage of the total amount you'd use:
要获得$NumberFour
您使用的总金额的百分比:
$percentage = ( $NumberFour / $Everything ) * 100;
回答by Rene Korss
Create function to calculate percentage between two numbers.
创建函数来计算两个数字之间的百分比。
<?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";
?>
This outputs
这输出
First of everything: 45.05%
Second of everything: 38.74%
Third of everything: 13.51%
Fourth of everything: 2.7%