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!
I used the answers from here and put them in a function, you can use it like this:
Once called,
echo $result
will be1
in this case, otherwise0
.The function:
Or a version with debug output:
Just save the function in a separated
.sh
file and include it like this:beware when comparing numbers that are package versions, like checking if grep 2.20 is greater than version 2.6:
I solved such problem with such shell/awk function:
Use korn shell, in bash you may have to compare the decimal part separately
awk
and tools like it (I'm staring at yoused
...) should be relegated to the dustbin of old projects, with code that everyone is too afraid to touch since it was written in a read-never language.Or you're the relatively rare project that needs to prioritize CPU usage optimization over code maintenance optimization... in which case, carry on.
If not, though, why not instead just use something readable and explicit, such as
python
? Your fellow coders and future self will thank you. You can usepython
inline with bash just like all the others.Pure bash solution for comparing floats without exponential notation, leading or trailing zeros:
Order of logical operators matters. Integer parts are compared as numbers and fractional parts are intentionally compared as strings. Variables are split into integer and fractional parts using this method.
Won't compare floats with integers (without dot).