php取整函数ceil,floor,round,intval函数的区别
单词ceil是天花板的意思;floor是地板的意思;round有约等于的意思;intval是取整的意思。
举几个简单的例子:
<?php $methods = array("ceil", "floor", "intval", "round"); $nums = array(1, 1.2, 1.5, -1.2, -1.5, '011', '009.a', 'a'); foreach($methods as $val){ foreach($nums as $v){ echo $val, "('", $v, "') = ", $val($v), "<br/><br/>"; } echo '<hr/>'; } /** * ceil('1') = 1 ceil('1.2') = 2 ceil('1.5') = 2 ceil('-1.2') = -1 ceil('-1.5') = -1 ceil('011') = 11 ceil('009.a') = 9 ceil('a') = 0 ---------------------------------- floor('1') = 1 floor('1.2') = 1 floor('1.5') = 1 floor('-1.2') = -2 floor('-1.5') = -2 floor('011') = 11 floor('009.a') = 9 floor('a') = 0 ---------------------------------- intval('1') = 1 intval('1.2') = 1 intval('1.5') = 1 intval('-1.2') = -1 intval('-1.5') = -1 intval('011') = 11 intval('009.a') = 9 intval('a') = 0 ---------------------------------- round('1') = 1 round('1.2') = 1 round('1.5') = 2 round('-1.2') = -1 round('-1.5') = -2 round('011') = 11 round('009.a') = 9 round('a') = 0 * */
php数字处理的时候难免会有保留小数位的需求。通常有几种方法,round(), number_format(), sprintf()
简单举两个例子:
$num1 = 12345.789; $num2 = 0.7; $round1 = round($num1, 2);// 12345.79 $round2 = round($num2, 2);// 0.7 $format1 = number_format($num1, 2, '.', '');// 12345.79 $format2 = number_format($num2, 2, '.', '');// 0.70 $format3 = number_format($num1, 2, '.', ',');// 12,345.79 $sprintf1 = sprintf('%.2f', $num1);// 12345.79 $sprintf2 = sprintf('%.2f', $num2);// 0.70
可以看出来,round($num, 2)这个函数是看$num的情况,如果$num本身就没有小数位或者不到2位,那么得到的结果也不是保留2位。
所以,如果希望确切的得到保留两位小数的情况,推荐使用number_format()这个用法,或者sprintf()这个。
number_format