Current Location: Home> Latest Articles> How to use ceil() to round up the decimals

How to use ceil() to round up the decimals

M66 2025-05-30

1. What is the ceil() function?

ceil() is a built-in function of PHP, which is used to perform operations on floating point numbers. No matter what the decimal point is, as long as it is not an integer, it will raise the number to the next closest integer.

Function syntax:

 ceil(float $num): float
  • $num : The floating point number that needs to be rounded.

  • Return value: The type is a floating point number, but the value is the result after rounding.


2. Basic usage examples

Let’s take a look at a simple example:

 <?php
$price = 10.1;
$rounded = ceil($price);
echo $rounded; // Output 11
?>

Even if the fractional part is only 0.1, ceil() will still carry it up to 11.

Let’s take a look at a few more examples:

 <?php
echo ceil(5.1);    // Output 6
echo "<br>";
echo ceil(5.9);    // Output 6
echo "<br>";
echo ceil(-5.1);   // Output -5(Negative numbers are approaching0)
?>

3. Common usage scenarios

1. Pagination function

Imagine that there are 157 pieces of data on a website and 10 pieces are displayed on each page, so how many pages are needed?

 <?php
$total_items = 157;
$items_per_page = 10;
$total_pages = ceil($total_items / $items_per_page);
echo $total_pages; // Output 16
?>

Whether or not it is just divisible, ceil() ensures that enough pages are displayed to display all data.

2. Calculate shipping charges or quantity of goods

If a product is 5 packs per pack and the customer orders 22, how many packs do the merchant need to prepare?

 <?php
$total_ordered = 22;
$per_pack = 5;
$packs_needed = ceil($total_ordered / $per_pack);
echo $packs_needed; // Output 5
?>

4. Comparison with other rounding functions

There are two related functions in PHP:

Let’s compare it below:

 <?php
$num = 4.3;
echo ceil($num);  // Output 5
echo floor($num); // Output 4
echo round($num); // Output 4
?>

Understanding the differences between the three will help to select the right function according to different business needs.


5. Application cases based on actual projects

Suppose we are developing a product ordering system. After the user selects the quantity, the system needs to dynamically calculate the total amount paid and round it up to the nearest integer price to avoid the problem of decimal payment.

 <?php
$url = "https://m66.net/checkout?price=" . $final_price;
echo "<a href='$url'>Check now</a>";
?>