How can I compare two floating point numbers in Bash?
I am trying hard to compare two floating point numbers within a Bash script. I have two variables, e.g.
let num1=3.17648e-22
let num2=1.5
Now, I just want do a simple comparison of these two numbers:
st=`echo "$num1 < $num2" | bc`
if [ $st -eq 1]; then
echo -e "$num1 < $num2"
else
echo -e "$num1 >= $num2"
fi
Unfortunately, I have some problems with the right treatment of the num1 which can be of the "e-format".
More conveniently
This can be done more conveniently using Bash's numeric context:
if (( $(echo "$num1 > $num2" |bc -l) )); then
…
fi
Explanation
Piping through the basic calculator command bc
returns either 1 or 0.
The option -l
is equivalent to --mathlib
; it loads the standard math library.
Enclosing the whole expression between double parenthesis (( ))
will translate these values to respectively true or false.
Please, ensure that the bc
basic calculator package is installed.
Caveat: Exponential notation should be written as *10^
; not E
, nor e
.
For example:
$ echo "1*10^3==1000" |bc
1
Whereas
$ echo "1E3==1000" |bc
0
Strategies to overcome this bc
limitation are discussed here.
Bash handles only integer maths, but you can use the bc
command as follows:
$ num1=3.17648E-22
$ num2=1.5
$ echo $num1'>'$num2 | bc -l
0
$ echo $num2'>'$num1 | bc -l
1
Note that the exponent sign must be uppercase.