如何将浮动百分比值转换为整数百分比?

时间:2012-05-03 19:35:33

标签: php

如何在PHP中将float percent number值转换为整数百分比数值?

示例:3.8461538461538%= 4%

更新: 这是我的代码,我编码得到百分比值,但我得到十进制值,但我需要它没有十进制值。

$total = array_sum($total_count);
$percent = ($occurs/$total)*100;
echo $percent ; 
echo "%";

3 个答案:

答案 0 :(得分:2)

这是通过round() - 舍入到最接近的

来完成的
<?php 
echo round('3.8461538461538'); //4
?>

还有:

floor() - 向下分数。

ceil() - 分数上升。

答案 1 :(得分:1)

使用round()。这是一个PHP函数。

修改 鉴于代码:

$total = array_sum($total_count);
 $percent = ($occurs/$total)*100;
 echo round($percent). "%";

例如:

$number="3.8461538461538%";   //if it's a string with % in the end.
$number=substr($number, 0,-1);  //It type converts automatically here. Lazy code :)
$number_rounded=round($number);

$number=3.8461538461538;  //If it's just a float.
$number_rounded=round($number);

答案 2 :(得分:0)

<?php number_format(3.8461538461538); ?>

您可以在第二个参数中指定小数点数(默认为0)。