How to compare two floating point numbers in Bash?
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" |bc1
Whereas
$ echo '1E3==1000" |bc0
Strategies to overcome this bc
limitation are discussed here.
bash handles only integer mathsbut you can use bc
command as follows:
$ num1=3.17648E-22$ num2=1.5$ echo $num1'>'$num2 | bc -l0$ echo $num2'>'$num1 | bc -l1
Note that exponent sign must be uppercase
It's better to use awk
for non integer mathematics. You can use this bash utility function:
numCompare() { awk -v n1="$1" -v n2="$2" 'BEGIN {printf "%s " (n1<n2?"<":">=") " %s\n", n1, n2}'}
And call it as:
numCompare 5.65 3.14e-225.65 >= 3.14e-22numCompare 5.65e-23 3.14e-225.65e-23 < 3.14e-22numCompare 3.145678 3.1456793.145678 < 3.145679