Home >Backend Development >PHP Tutorial >PHP四舍五入精确小数位及取整方法

PHP四舍五入精确小数位及取整方法

WBOY
WBOYOriginal
2016-06-20 13:05:02920browse

文章将使用php对数字进行四舍五入保留N位小数,以及使用php对数字进行取整的方法做个小总结。

(1)php保留三位小数并且四舍五入

<p>$num=0.0215489;</p><p>echo sprintf("%.3f", $num); // 0.022</p>

(2)php保留三位小数不四舍五入

<p>$num=0.0215489;</p><p>echo substr(sprintf("%.4f", $num),0,-1); // 0.021</p>

(3)php进一法取整数(这个在分页程序的页数程序里面会用到)

<p>echo ceil(4.3);    // 5</p><p>echo ceil(9.999);  // 10</p>

(4)php舍去法取整数

<p>echo floor(4.3);   // 4</p>echo floor(9.999); // 9


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn