Floating Point in Bash Shell

Integers are natively supported in Bash shell. However, what if we use floating point in Bash shell?

The short and direct answer is using bc‘ command – “An arbitrary precision calculator language.”

Just run bc  and enter some floating point calculation expression, such as “1.2+8.2”, bc will give the result.

In a script, we certainly need a more automatic way. This is a piece of simple script:

$ echo "scale=4; $*" | bc -q

For example, to calculate “1.2+8.2”

$ echo "scale=4; 1.2+8.2" | bc -q

and you will get 9.4 .

“By default bc outputs its result with no digits to the right of the decimal point and without a decimal point. To change this you have to change one of bc‘s builtin variables: scale. This is where the “language” features of bc are relevant, in bc as in C statements are separated by semi-colons.”

For more detailed tutorial on bc, I suggest: Floating Point Math in Bash by Mitch Frazier.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *