Bash Script That Prints A Number With Two Decimal Places
Another task that I had to tackle as part of the lessons on shell expansion in my ongoing ALX Software Engineering course was to write a bash script that prints a number with two decimal places.
Let's take a practical example and solve it to explain how to print a number with two decimal places.
Write a script that prints a number with two decimal places, followed by a new line.
The number will be stored in the environment variable MYNUM
Up until this point, we had always relied on the
echo command to display or print somethings to the screen. As such, upon reading this question, my intuition defaulted to using the
echo command to perform the task.
Unfortunately, I learned too soon that the
echo command prints out only whole numbers and doesn't print floats by default. This means that we need to rely on something else to help us print floats or decimal numbers to the screen.
printf command is the saviour of the situation. This is a popular command in programming languages like C but the bash shell equally utilizes it for the same purpose.
Printf is able to let us determine the format of the output we want. Hence, in this case the
printf command will help us to format the output to be in 2 decimal places.
How to format output with the
Let's look at the normal synthax of the
printf options arguments
It may also be presented as
printf options [format specifiers] arguments
The format specifiers are what tells the
printf command what the format of the output should be. They also point to the arguments and restricts the type or format of values the
printf command takes in as arguments.
Examples of format specifiers that you are likely to use include
|decimal (integer) number (base 10)
|integer number (base 10)
|octal number (base 8)
|hexadecimal number (base 16)
Did you find this article valuable?
Support Dr. Ehoneah Obed by becoming a sponsor. Any amount is appreciated!