经常用到取整的函数,今天小小的总结一下!其实很简单,就是几个函数而已~~主要是:ceil,floor,round,intval
进一法取整、四舍五入取整、忽略小数等的取整数方法大全
PHP取整数函数常用的四种方法,下面收集了四个函数;经常用到取整的函数,今天小小的总结一下!其实很简单,就是几个函数而已~~主要是:ceil,floor,round,intval
PHP取整数函数常用的四种方法,下面收集了四个函数;
经常用到取整的函数,今天小小的总结一下!其实很简单,就是几个函数而已~~主要是:ceil,floor,round,intval
一、ceil — 进一法取整
说明
float ceil ( float value )
返回不小于 value 的下一个整数,value 如果有小数部分则进一位。ceil() 返回的类型仍然是 float,因为 float 值的范围通常比 integer 要大。
例子 1. ceil() 例子,代码如下:
echoceil(4.3);// 5
echoceil(9.999);// 10
?>
二、floor — 舍去法取整
说明:
float floor ( float value )
返回不大于 value 的下一个整数,将 value 的小数部分舍去取整。floor() 返回的类型仍然是 float,因为 float 值的范围通常比 integer 要大。
例子 1. floor() 例子,代码如下:
echofloor(4.3);// 4
echofloor(9.999);// 9
?>
三、round — 对浮点数进行四舍五入
说明:
float round ( float val [, int precision] )
返回将 val 根据指定精度 precision(十进制小数点后数字的数目)进行四舍五入的结果。precision 也可以是负数或零(默认值)。
例子 1. round() 例子,代码如下:
echoround(3.4);// 3
echoround(3.5);// 4
echoround(3.6);// 4
echoround(3.6, 0);// 4
echoround(1.95583, 2);// 1.96
echoround(1241757, -3);// 1242000
echoround(5.045, 2);// 5.05
echoround(5.055, 2);// 5.06
?>
四、intval—对变数转成整数型态
例子intval(),代码如下:
echointval(4.3);//4
echointval(4.6);// 4
?>
PHP四舍五入精确小数位及取整
(1)php保留三位小数并且四舍五入,代码如下:
$num=0.0215489;
echosprintf("%.3f",$num);// 0.022
(2)php保留三位小数不四舍五入,代码如下:
$num=0.0215489;
echosubstr(sprintf("%.4f",$num),0,-1);// 0.021
(3)php进一法取整数(这个在分页程序的页数程序里面会用到),代码如下:
echo ceil(4.3); // 5
echo ceil(9.999); // 10
(4)php舍去法取整数,代码如下:
echo floor(4.3); // 4
echo floor(9.999); // 9
(5),round函数
例 1. round() 例子,代码如下:
echoround(3.4);// 3
echoround(3.5);// 4
echoround(3.6);// 4
echoround(3.6, 0);// 4
echoround(1.95583, 2);// 1.96
echoround(1241757, -3);// 1242000
echoround(5.045, 2);// 5.05
echoround(5.055, 2);// 5.06
?>
PHP四舍五入保留两位小数点最精确的方法,代码如下:
$number= 123213.066666;
echosprintf("%.2f",$number);
?>
输出结果:123213.07