convert scientific notation to decimal in bash

kimmyjo221 picture kimmyjo221 · Dec 11, 2012 · Viewed 16.5k times · Source

I would like to convert a number that is stored in scientific notation into a floating point decimal, so I can then perform some comparisons on the data. This is being done in a bash script - here is a small snippet of the code:

while read track_id landfall_num gate_id pres_inter
do
  if [[ $landfall_num == 0001 ]]
  then
     start_flag = true
     echo DING DING $start_flag
     if [[ $pres_inter < 97000 ]]
     then
        echo Strong Storm From North $track_id, $gate_id, $pres_inter
     fi
  fi
done < $file

My problem is that my < operand is selecting basically all of the pressure values, which are stored in scientific notation, when I use <, and none when I use >. I am looking at atmospheric pressure measurements in pascals rather than millibars.

Here is sample output:

Strong Storm From North 0039988 0017 1.0074E+05

Strong Storm From North 0037481 0018 9.9831E+04

Neither of these storms should be meeting the selection criteria!

Answer

gniourf_gniourf picture gniourf_gniourf · Dec 11, 2012

First thing, bash cannot do arithmetic using floating point arithmetic. Second thing, bash doesn't know scientific notation (even for integers).

First thing you can try, if you're absolutely positively sure that all your numbers are integers: convert them to decimal notation: printf will happily do that for you:

printf -v pres_inter "%.f" "$pres_inter"

(%.f rounds to nearest integer).

then use bash's arithmetic:

if (( pres_inter < 97000 )); then ....

This solution is wonderful and doesn't use any external commands or any subshells: speed and efficiency!

Now if you're dealing with non integers you'd better use bc to do the arithmetic: but since bc is retarded and doesn't deal well with the scientific notation, you have to convert your numbers to decimal notation anyways. So something like the following should do:

printf -v pres_inter "%f" "$pres_inter"
if (( $(bc -l <<< "$pres_inter<97000") )); then ...

Of course, this is slower since you're forking a bc. If you're happy with integers, just stick to the first possibility I gave.

Done!