Displaying Decimal Number in Shell Scripts

Have you ever wanted to display a decimal number on your shell scripts? Bash by default is not able to display any decimal number and only plays well with integers.

There's a solution for this, which is by using bc, a simple calculator which is mostly provided in any Linux distributions. Let's play a bit with bc.

In order to display a decimal number using bc, you will have to define a scale variable. Please have a look on bc's manual page for detail. Use this command on your terminal to try it: echo "scale=4; 3/4" | bc -l. It will give you an output of .7500

Here's a simple script for a demo:


while true; do
echo -n "Enter your score [0-100] ('q' for quit): ";
read SCORE;
if (("$SCORE" < "0")) || (("$SCORE" > "100")); then
echo "Be serious. Come'on, try again: "
elif [ "$SCORE" == "q" ]; then
echo -e "Average rating: \c"
result=`echo "scale=4; $SUM/$NUM" | bc -l`
echo "$result"
NUM=$[$NUM + 1]

Try running it:
Enter your score [0-100] ('q' for quit): 1
Enter your score [0-100] ('q' for quit): 5
Enter your score [0-100] ('q' for quit): 4
Enter your score [0-100] ('q' for quit): q
Average rating: 3.3333

Popular posts from this blog

Python 3.6.0 in SBo 14.2 repository

NVidia Legacy Unix Driver Update

Security Update: Thunderbird, Seamonkey, libpng, python, samba