我目前正在划分两个值,以便从我的应用程序的实际计数和总计数中获得百分比。
我正在使用以下公式:
echo ($fakecount / $totalcount) * 100;
这给了我一个类似的值:79.2312313。我更喜欢 79% 这样的值。
我尝试了以下方法:
echo round($fakecount / $totalcount) * 100;
这似乎无法正常工作。
有什么建议么?
您需要在四舍五入之前乘以 100,而不是之后:
echo round($fakecount * 100 / $totalcount);
您正在计算$fakecount / $totalcount
,这将是一个介于 0 和 1 之间的数字,然后将其四舍五入,得到 0 或 1,然后乘以 100,得到 0 或 100 作为您的百分比。
尝试,
echo (int)($fakecount * 100 / $totalcount + .5);
这是有效的,因为如果小数部分是,添加 0.5 会使整数部分增加 1>= .5
或者,
round ($fakecount * 100 / $totalcount);
请注意,我在除法之前乘以 100 以更好地保持精度。
echo intval(($fakecount / $totalcount) * 100);
或者你可以使用
echo floor(($fakecount / $totalcount) * 100); //Round down
或者
echo ceil(($fakecount / $totalcount) * 100); // Round Up
使用 round() 函数
echo round(($fakecount / $totalcount) * 100);
http://php.net/manual/en/function.round.php
你可以使用的其他人是
没有...
有很多方法可以做到这一点。
$mypercent = ($fakecount / $totalcount) * 100;
请记住..这将首先运行 (xxx) 内部的内容,然后运行 100。
在这之后...
echo round($mypercent);
如果你愿意,你也可以使用很多规则......
<i>if ($value < 10) {
$value = floor($value);
} else {
$value = round($value);
}</i>
不要忘记查看其他命令,也许你会需要它。
ceil() - 向上取整分数
floor() - 向下舍入分数
=)