In Bash, it only handle integers, so any decimal places are discarded when dividing integers.
There may be times when you want to round or round up the result of a division, so, I will introduce how to round, round up, or round down for decimal places.
1. Floor
If you discard the decimal part of the division operation, it will be calculated as follows.
- 2 / 2 = 1
- 5 / 2 = 2
- 5 / 3 = 1
Basically, since the shell discards the fractional part of a real number, you can divide integers as follows in Bash.
#!/bin/bash
a=$(( 2 / 2 ))
b=$(( 5 / 2 ))
c=$(( 5 / 3 ))
echo "a=${a}"
echo "b=${b}"
echo "c=${c}"
Output:
$ bash example.sh
a=1
b=2
c=1
2. Ceil
If you round up the decimal part of a division operation, the calculation will be as follows.
- 2 / 2 = 1
- 5 / 2 = 3
- 5 / 3 = 2
To round up the division result of A and B in the shell, you can use a mathematical trick to calculate A / B = (A + B - 1) / B
.
In this example, I implemented a function ceiling()
to round up the devided number from 2 integers.
#!/bin/bash
ceiling() {
result=$(( ($1 + $2 - 1) / $2 ))
echo $result
}
a=$(ceiling 2 2)
b=$(ceiling 5 2)
c=$(ceiling 5 3)
echo "a=${a}"
echo "b=${b}"
echo "c=${c}"
Output:
$ bash example.sh
a=1
b=3
c=2
3. Round off
If you round off the decimal part of a division operation, it will be calculated as follows.
- 2 / 2 = 1
- 5 / 2 = 3
- 4 / 3 = 1
To round the result of the division of A and B in the shell, use a mathematical trick to calculate A / B = (A + (B / 2)) / B
.
In this example, I implemented a function roundOff()
to round off the devided number from 2 integers.
#!/bin/bash
roundOff() {
result=$(( ($1 + ($2 / 2)) / $2 ))
echo $result
}
a=$(roundOff 2 2)
b=$(roundOff 5 2)
c=$(roundOff 4 3)
echo "a=${a}"
echo "b=${b}"
echo "c=${c}"
Output:
$ bash example.sh
a=1
b=3
c=1
Related Posts
- How to measure elapsed time in Bash
- Ceil, Floor, Round off a devided number in Bash
- Check if a number is Positive or Negative in Bash
- How to Print a Variable in Bash
- Number Comparison Operators in Bash
- Convert between Uppercase and Lowercase in Bash
- Check if a File or Directory exists in Bash
- How to extract substring in Bash
- Bash Case Statement with examples
- How to use Command Line Arguments in Bash
- How to use Arrays in Bash
- How to Compare strings in Bash Shell
- if..else statement in Bash
- Add, Subtract, Multiply, Division with Numbers in Bash
- Bash For, Whlie Loop Examples
- How to Pass and Use command line arguments in Bash