Skip to content
Tutorials Center
My learning

Topics

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
<?php
echo ceil(4.1);    // 5
echo floor(4.9);   // 4

Try it

PHP Up, down and toward zero

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.

PHP Pagination and rounding to a step

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

PHP
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)) prints float(5). Cast with (int) after rounding, or the value may print as 5 in echo but behave as a float in strict comparisons and array keys (float keys trigger a deprecation when they have decimals, but 5.0 is converted silently).
  • Negative numbers. ceil(-4.5) is -4 and floor(-4.5) is -5. Use (int) to truncate toward zero, or intdiv() for integer division that truncates.
  • ceil(-0.5) returns -0, a negative zero that prints as -0. Add + 0 or cast to int if 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; use round() or the bcmath functions 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.
  • NAN and INF are returned unchanged.