2013-02-14 79 views
-2

如何实现百分比计算:PHP百分比计算

$x=3; 
$y = 100\$x; // 3.333.. 
$x*$y - and here I need to get 100 without Observational error 

任何想法?

+0

'100 \ $ x'?这不是分区......它是一个命名空间参考,并且无法启动。计算一个百分比只是基本的数学。事实上,你使用PHP(或任何其他语言)不会改变你如何计算百分比... – 2013-02-14 17:05:27

+3

100/3不是3.33333开始... – geoffspear 2013-02-14 17:07:38

+0

我认为百分比是在小学教的。 – 2013-02-14 17:08:03

回答

27

您的反斜杠(\)不是分割符号。您必须使用分区/符号。

下面是一个使用number_format()的示例,它将四舍五入到小数点后两位(百分之一位置)。

$x = 3; 
$y = 15; 

$percent = $x/$y; 
$percent_friendly = number_format($percent * 100, 2) . '%'; // change 2 to # of decimals 
+1

这不是一个百分比。这只是除以100. – 2013-02-14 17:06:14

+0

@MarcB更正 – 2013-02-14 17:06:44