PHP: Rounding a number up.

This is a beginners guide on how to round a decimal number up using PHP’s ceil function.

Let’s say for example that you have a decimal number and you want to round that number up to next highest integer value. i.e. You want “1.3” to become “2” and you want “7.893” to become “8”, etc.

In this case, we would use PHP’s ceil function like so:

<?php

//Our example number.
$number = 1.734;

//Using the ceil function.
//1.734 becomes 2.
echo ceil($number);

If you run the code above, you will see that PHP’s ceil function will round “1.734” to “2”.

ceil accepts one parameter. In most cases, you will be passing it a float / decimal value. If you pass it an integer value, it will simply return the same number as a float.

If you do a var_dump on the return value from ceil, you will see that it is a float value:

//Our example number.
$number = 8.01;

//var_dump it.
var_dump(ceil($number));

The PHP above will output: “float 9”.

Float value.

According to the manual, ceil returns a float value because “the range of float is usually bigger than that of integer.” If that fact bothers you, then you could always parse the return value as an integer value by using the intval function like so:

//Our example number.
$number = 11.034;

//var_dump it.
$roundedUpNumber = ceil($number);

//Parse it as an integer.
$intNumber = intval($roundedUpNumber);

//var_dump it.
var_dump($intNumber);

The code above will output: “int 12”.

Negative numbers and ceil.

So, what happens if we provide ceil with a negative number?

//A negative number.
$number = -4.2;

//var_dump it.
$roundedUpNumber = ceil($number);

//var_dump it.
var_dump($roundedUpNumber);

If you run the PHP code above, you will see that ceil rounded our negative number “-4.2” up to “-4”. This is because “-4” is a larger number than “-4.2”. If you are using ceil with negative numbers, you kind of have to think as though it works the opposite way.

Hopefully, this article cleared a few things up!