Floating point stuff in Bash
Monday, January 30th, 2006
Shell scripting is powerful, but unfortunatelly it gets less easy if you want to perform floating point calculations in it. There’s expr
, but it only handles integers:
[todsah@jib]~$ echo `expr 0.1 + 0.1` expr: non-numeric argument
If you wish to perform floating point calculations in shell scripts, you can use the bc tool: “bc – An arbitrary precision calculator language“.
Some examples:
[todsah@jib]~$ A=`echo "0.1 + 0.1" | bc`; echo $A; .2
However, dividing two numbers in bc, which would result in a fractured (floating point) number, doesn’t work out-of-the-box. So you’ll need to set the scale variable:
[todsah@jib]~$ A=`echo "10 / 3" | bc`; echo $A; 3 [todsah@jib]~$ A=`echo "scale = 2; 10 / 3" | bc`; echo $A; 3.33
You can also evaluate boolean expressions using bc:
[todsah@jib]~$ if [ `echo "10.1 < 10" | bc` -eq 1 ]; then echo "10.1 < 10"; fi [todsah@jib]~$ if [ `echo "10.1 > 10" | bc` -eq 1 ]; then echo "10.1 > 10"; fi 10.1 > 10
This function might prove to helpful:
function fpexpr() { scale=$1 shift expr=$* echo `echo "scale = $scale; $expr" | bc` }
For example:
[todsah@jib]~/notes/work/organisatorisch$ A=`fpexpr 5 "10 / 3"^J`; echo $A; 3.33333
bc can do a lot more than this. Consult the manual page for other handy stuff.