search
Homephp教程php手册php中的四舍五入函数代码(floor函数、ceil函数、round与intval)

php 中处理浮点数时经常要需要四舍五入。在php 中有两个函数适用于这种情况:floor函数、ceil函数和round函数

floor函数和ceil函数互相搭配起来可以使php 处理的数据更加真实可靠。

一、先来看floor函数:

语法:

float floor ( float value )

说明:

返回不大于 value 的下一个整数,将 value 的小数部分舍去取整。floor() 返回的类型仍然是 float,因为 float 值的范围通常比 integer 要大。

floor() 例子 1

floor() 例子 2

输出:
0
0
5
5
-6
-6

二、ceil函数:

语法:

float ceil ( float value )

说明:

返回不小于 value 的下一个整数,value 如果有小数部分则进一位。ceil() 返回的类型仍然是 float,因为 float 值的范围通常比 integer 要大。

ceil() 例子:

看到这两个函数的区别了么。。

在分页时我们会常用到的
//页码计算:

$lastpg=ceil($totle/$displaypg); //最后页,也是总页数,用ceil就方便多了。 $lastpg=$lastpg ? $lastpg : 1; //没有显示条目,,置最后页为1 $page=min($lastpg,$page); $prepg=$page-1; //上一页 $nextpg=($page==$lastpg ? 0 : $page+1); //下一页 $firstcount=($page-1)*$displaypg;

当然,如果需要制定精度就需要使用round函数了。

三、round函数:

语法:

float round ( float val [, int precision] )

说明:

返回将 val 根据指定精度 precision(十进制小数点后数字的数目)进行四舍五入的结果。precision 也可以是负数或零(默认值)。

round() 例子

四、intval—对变数转成整数型态

变量转成整数类型。

语法: int intval(mixed var, int [base]);

返回值: 整数

函数种类: PHP 系统功能
 
内容说明


本函数可将变量转成整数类型。可省略的参数 base 是转换的基底,默认值为 10。转换的变量 var 可以为数组或类之外的任何类型变量。

例子intval()

注:intval如果是字符型的会自动转换为0 如

intval('abc');

输出结果 0

如果是

intval('5fd');

输出结果是

5

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft