In this article we introduced four commonly used rounding and rounding functions in php, ceil, floor, round, intval. Let’s introduce them in detail below.
1.ceil: rounding to the nearest integer
Explanation
float ceil (float value)
Returns the next integer that is not less than value, if value has decimals Partially advances one digit. The type returned by ceil() is still float because the range of float values is usually larger than that of integer.
Example 1. ceil() example
<?php echo ceil(4.3); // 5 echo ceil(9.999); // 10 ?>
We will often use it when paging
//Page number calculation:
$lastpg=ceil($totle/$displaypg); //最后页,也是总页数 $lastpg=$lastpg ? $lastpg : 1; //没有显示条目,置最后页为1 $page=min($lastpg,$page); $prepg=$page-1; //上一页 $nextpg=($page==$lastpg ? 0 : $page+1); //下一页 $firstcount=($page-1)*$displaypg;
2.floor: Rounding by rounding method
Explanation
float floor (float value)
Returns the next integer that is not greater than value, and rounds the decimal part of value. The type returned by floor() is still float because the range of float values is usually larger than that of integer.
Example 1. floor() example
Example
In this example, we will apply the floor() function to different numbers:
<?php echo(floor(0.60)); echo(floor(0.40)); echo(floor(5)); echo(floor(5.1)); echo(floor(-5.1)); echo(floor(-5.9)) ?>
Output:
0 0 5 5 -6 -6
3.round: Round floating point numbers
Description
float round (float val [, int precision])
Returns val according to the specified precision (the number of decimal digits after the decimal point) rounded. precision can also be negative or zero (default).
Note: PHP cannot handle strings like "12,300.2" correctly by default.
Note: The prec parameter was introduced in PHP 4. .
Example
<?php echo(round(0.60)); echo(round(0.50)); echo(round(0.49)); echo(round(-4.40)); echo(round(-4.60)); ?>
Output:
1 1 0 -4 -5
4.intval: Convert variables into integer types
Convert variables into Integer type.
Syntax: int intval(mixed var, int [base]);
Return value: integer
Function type: PHP system function
Content description
This function can convert variables into integer types. The omitted parameter base is the base of the conversion, with a default value of 10. The converted variable var can be any type variable except an array or class.
Example intval()
<?php echo intval(4.3); //4 echo intval(4.6); // 4 ?>
Note: If intval is a character type, it will be automatically converted to 0. For example,
intval('abc');
output the result
0
If it is
intval('5fd');
the output result is
5
5.What is the difference between the ceil function and the intval function in php?
ceil is rounded to the nearest integer, intval gets the integer value of the variable
ceil(3.33)=4; intval(3.33)=3; ceil(3.9)=4; intval(3.9)=3;
Related articles:
php data processing rounding, rounding
3 ways to implement rounding in PHP
Summary of methods for rounding and intercepting floating-point strings in PHP