Home > php教程 > php手册 > PHP四舍五入精确小数位及取整

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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-13 09:46:13
Original
925 people have browsed it

php中取小数位的函数有sprintf,ceil,floor,round等等函数来实现四舍五入,下面我们就一起来看看具体的实例吧。

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

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

 代码如下 复制代码

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


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

 

 代码如下 复制代码
$num=0.0215489;
echo substr(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() 例子

 代码如下 复制代码

echo round(3.4);         // 3
echo round(3.5);         // 4
echo round(3.6);         // 4
echo round(3.6, 0);      // 4
echo round(1.95583, 2);  // 1.96
echo round(1241757, -3); // 1242000
echo round(5.045, 2);    // 5.05
echo round(5.055, 2);    // 5.06
?> 

source:php.cn
Statement of this Website
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template