When encountering a situation in PHP where the result of division needs to be rounded, the following method needs to be used:
1. round: rounding up
The round() function rounds floating point numbers.
Syntax: round(x, prec)
Parameter Description
x Optional. Specifies the number to be rounded.
prec is optional. Specifies the number of digits after the decimal point.
Description: Returns the result of rounding x to the specified precision prec (the number of decimal digits after the decimal point). prec can also be negative or zero (default).
Tip: PHP cannot handle strings like "12,300.2" correctly by default.
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
-52. ceil: round up
The ceil() function rounds up to the nearest integer.
Syntax: ceil(x)
Parameter Description
x is required. Specifies the number to be rounded.
Description: Returns the next integer that is not less than x. If x has a decimal part, it will be rounded up by one. The type returned by ceil() is still float because the range of float values is usually larger than that of integer.
Example:
<?php
echo(ceil(0.60);
echo(ceil(0.40);
echo(ceil(5);
echo(ceil(5.1);
echo(ceil(-5.1);
echo(ceil(-5.9));
?>Output:
1
1
5
6
-5
-53. floor: round down
The floor() function rounds down to the nearest integer.
Syntax: floor(x)
Parameter Description
x is required. Specifies the number to be rounded.
Description: Return the next integer not greater than x, and round off the decimal part of x. The type returned by floor() is still float because the range of float values is usually larger than that of integer.
Example:
<?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