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
- This means negative numbers will be rounded UP
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.