Skip to content

Core\Math::ceil

Rounds a number up to the next whole number. 4.1 becomes 5.0, and a number that is already whole stays the same.

For a negative number, up means toward zero: -4.1 becomes -4.0. A number between -1.0 and 0.0 becomes -0.0, which prints as -0. The result is always a float. NaN (a value that means "not a number") and the infinities stay the same.

Use it when a part still needs a whole one: a page that is only half full is still a page, and a box with one item in it is still a box. Core\Math::floor rounds down, and Core\Math::round rounds to the nearest number.

The examples below show a few numbers rounded up, then negative numbers, then how a list finds how many pages it needs.

Parameters

  • $nfloatThe number to round up.

Return value

Returns float. A whole number, as a float. A $n between -1.0 and 0.0 gives -0.0. NaN and the infinities stay the same.

Examples

Rounding up

<?nvs
// Shows how `Core\Math::ceil` rounds a number up to the next whole number.
// Any fraction rounds up. This prints 5.
echo Core\Math::ceil(4.1), "\n";
// A very small fraction rounds up too. This prints 5.
echo Core\Math::ceil(4.0001), "\n";
// A whole number stays the same. This prints 4.
echo Core\Math::ceil(4.0), "\n";
Output
5
5
4

Negative numbers

<?nvs
// Shows how `Core\Math::ceil` rounds negative numbers.
// Up means toward zero for a negative number. This prints -4.
echo Core\Math::ceil(-4.1), "\n";
// A number between -1.0 and 0.0 gives zero with a minus sign. This prints -0.
echo Core\Math::ceil(-0.5), "\n";
// `Core\Math::floor` rounds the other way. This prints -5.
echo Core\Math::floor(-4.1), "\n";
Output
-4
-0
-5

How many pages

<?nvs
// Shows how a list of search results finds how many pages it needs.
class Pages
{
// A page that is only partly full still counts as a page.
public static function count(float $results, float $perPage): float
{
return Core\Math::ceil($results / $perPage);
}
}
// 47 results, 10 on each page. The last page has 7 results. This prints 5.
echo Pages::count(47.0, 10.0), "\n";
// 40 results fill exactly 4 pages. This prints 4.
echo Pages::count(40.0, 10.0), "\n";
// One result still needs one page. This prints 1.
echo Pages::count(1.0, 10.0), "\n";
Output
5
4
1