Bash: How to Calculate Ceiling of a Division Result


When you perform division in Bash, the result is rounded to the floor by default.

To instead perform ceiling rounding, you can use the following syntax:

(( result=(num1+num2-1)/num2 ))

This particular example divides the variable named $num1 by the variable named $num2 and rounds the result up to the nearest integer.

The resulting integer is stored in a variable named $result.

This syntax uses a mathematical fact that you can perform ceiling rounding by using the following formula:

  • Ceiling(X, Y) = (X+Y-1) / Y

For example, suppose X is 10 and Y is 4. The result of 10 / 4 is 2.5.

However, we can perform ceiling rounding by using the following formula:

  • Ceiling(X, Y) = (X+Y-1) / Y
  • Ceiling(10, 4) = (10+4-1) / 4
  • Ceiling(10, 4) = 13 / 4
  • Ceiling(10, 4) = 3.25

By default, Bash will perform floor rounding and return 3 as a result, which is the equivalent of 10 / 4 rounded up to the nearest integer.

The following example shows how to use this syntax in practice.

Example: How to Calculate the Ceiling of a Division Result in Bash

Suppose that we create the following two variables in Bash named $num1 and $num2:

  • $num1=10
  • $num2=4

Suppose that we divide $num1 by $num2 by using the following syntax:

num1=10
num2=4

(( result=num1/num2 ))
echo $result

The following screenshot shows how to use this syntax in practice:

Notice that Bash performs the division operation 10 / 4, which is 2.5 and it performs floor rounding by default to return 2 as a result.

To instead perform ceiling rounding, we can use the following syntax:

num1=10
num2=4

(( result=(num1+num2-1)/num2 ))
echo $result

The following screenshot shows how to use this syntax in practice:

Bash ceiling rounding

This time Bash performs the division operation 10 / 4, which is 2.5 but now it performs ceiling rounding to return 3 as a result.

Feel free to replace $num1 and $num2 with whatever values you would like to use in your own division problem.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Round Numbers to 2 Decimal Places
Bash: How to Calculate the Average of a Column
Bash: How to Find Minimum and Maximum Values in Array

Leave a Reply