PHP Reference ยท Math Functions
PHP ceil() and floor() functions
Reference for PHP ceil() and floor(): round a number up or down to a whole number, why they return floats, negative numbers, and pagination examples.
ceil() rounds a number up to the next whole number, and floor() rounds it down to the previous one. "Up" and "down" always mean toward positive and negative infinity, so ceil(-2.5) is -2 and floor(-2.5) is -3. They are different from round(), which goes to the nearest whole number, and from casting with (int), which cuts off the decimals toward zero.
Both functions return a float, even though the value is whole. Convert with (int) when you need an integer, for example for an array index or a page count.
<?php echo ceil(4.1); // 5 echo floor(4.9); // 4
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
ceil(int|float $num): float floor(int|float $num): float
| Name | Description |
|---|---|
$num |
The number to round. Numeric strings are converted first. |
Return value: a float holding a whole number. ceil() gives the smallest whole number that is not less than $num, and floor() gives the largest whole number that is not greater than $num.
Errors: a TypeError if the argument is not numeric.
Usage notes
- Always floats.
var_dump(ceil(4.1))printsfloat(5). Cast with(int)after rounding, or the value may print as5inechobut behave as a float in strict comparisons and array keys (float keys trigger a deprecation when they have decimals, but5.0is converted silently). - Negative numbers.
ceil(-4.5)is-4andfloor(-4.5)is-5. Use(int)to truncate toward zero, orintdiv()for integer division that truncates. ceil(-0.5)returns-0, a negative zero that prints as-0. Add+ 0or cast tointif you display it.- Decimal places: neither function has a precision argument. Multiply, round and divide (
floor($x * 100) / 100), but remember that binary floats cannot represent most decimals exactly; useround()or thebcmathfunctions for money. - Pagination:
ceil($total / $perPage)is the standard page count. - Very large floats (above 2^53) are already whole numbers and come back unchanged.
NANandINFare returned unchanged.
Related
round(),intdiv(),fmod(),abs(),max()andmin()- Lessons: Math functions, Numbers