Home » Programming » PHP » Php Ceil

Rounding Numbers Up with the PHP ceil() Function, with Examples

This short tutorial will cover how to use the PHP ceil() function to round numbers UP – and provide some code examples.

The PHP ceil() function rounds a number up (and only up!) to the nearest integer.

To round a number down to the nearest integer, use the floor() function instead.

To round a number normally, or for more options when rounding a number, use the round() function.

PHP ceil() Function Syntax

The syntax for the PHP ceil() function is as follows:

ceil($NUMBER)

Note that:

  • $NUMBER is the float or integer number you wish to perform the ceil() operation on
  • ceil() will return a float type number regardless of the type of number passed to it
    • The returned number will still be a whole integer – The float type is only used because it supports storing a larger range of numbers
  • ceil() will return the next highest whole number – NOT the next number furthest from 0

Code Examples

The ceil() function is pretty simple, so let’s look at some simple examples.

Below, several positive and negative numbers are passed to the PHP ceil() function so that you can see how they are rounded:

echo ceil(5);   // 5
echo ceil(8.1);   // 9
echo ceil(6.9999); // 7
echo ceil(-2.2); // -2
echo ceil(0); // 0

…The result of each ceil() call will be printed using the echo command (and the result is also shown in the code as a comment following each line).

The ceil() function can be helpful for things like calculating estimates for billing purposes – if you have calculated a price for multiple items, each with varying tax rates, you may have a gnarly looking number that you don’t want to supply to the customer – the ceil() function could be used to round that number up to a tidy integer value for printing on a quote or invoice.

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment