Bash: Performing floating arithmetic using bc

This may come as a surprise, but Bash only supports integer arithmetic natively.  If you need to perform calculations on floating point numbers, you will need to call out to a utility program like bc or Python.

As a quick proof to yourself, try multiplying integers, then do the same with floating point numbers.

$ echo $((2*3))
6

$ echo $((2.5*3))
bash: 2.5*3: syntax error: invalid arithmetic operator (error token is ".5*3")

To perform floating point operations, one way is to use the simple calculator utility, bc.

$ echo "2.5*3" | bc
7.5

# formatting using awk
$ echo "2.5*3" | bc | awk '{ printf("%.4f\n",$1) '}
7.500

Another way is to use Python.

python -c "print('{0:0.4f}'.format(2.5*3))"

And yet another way is to use awk.

awk 'BEGIN {printf "%.4f\n", 2.5*3}'

 

REFERENCES

gnu, bc reference

linux journal, floating point arithmetic in Bash

mathblog, floating point arithmetic in BASH