2012-05-03 132 views
-3

如何将浮动百分比数值转换为PHP中的整数百分比数值?如何将浮点百分比值转换为整数百分比?

例如:3.8461538461538%= 4%

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

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

你试过了什么? (什么是*类型的值?字符串?一个数字?) – 2012-05-03 19:36:36

回答

0
<?php number_format(3.8461538461538); ?> 

可以在S指定第二个参数是小数点的数量(默认值为0)。

+1

@Jennifer number_format( )用于转换数字格式。具体来说,创建以逗号分隔的货币值。因此,它会在很多方面比圆形()更重。 我不明白为什么这是'正确'的答案,而不是round()。 :-) – Niranjan

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); 
+0

请参阅:[PHP文档](http://php.net/manual/en/function.round.php) – Niranjan

2

这与round()做 - 舍入到最接近的INT

<?php 
echo round('3.8461538461538'); //4 
?> 

还有:

floor() - 舍去法取整。

ceil() - 圆形部分向上。