I am trying hard to compare two floating point numbers within a bash script. I have to 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". :(
Any help, hints are welcome!
More conveniently
This can be done more conveniently using Bash's numeric context:
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.Using bashj (https://sourceforge.net/projects/bashj/ ), a bash mutant with java support, you just write (and it IS easy to read):
Of course bashj bash/java hybridation offers much more...
A solution supporting the scientific notation with both uppercase and lowercase exponents (e.g.,
12.00e4
):Of course, if you don't need really floating-point arithmetic, just arithmetic on e.g. dollar values where there are always exactly two decimal digits, you might just drop the dot (effectively multiplying by 100) and compare the resulting integers.
This obviously requires you to be sure that both values have the same number of decimal places.
bash handles only integer maths but you can use
bc
command as follows:Note that exponent sign must be uppercase
you can use awk combined with a bash if condition, awk will print 1 or 0 and those will be interpreted by if clause with true or false.