How to compare two floating point numbers in Bash?

前端 未结 17 2170
無奈伤痛
無奈伤痛 2020-11-22 02:17

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

No

17条回答
  •  無奈伤痛
    2020-11-22 02:56

    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.

    This equally works for floats in scientific format, provided a capital letter E is employed, e.g. num1=3.44E6

提交回复
热议问题