How to compare two floating point numbers in Bash?

前端 未结 17 2164
無奈伤痛
無奈伤痛 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:37

    Pure bash solution for comparing floats without exponential notation, leading or trailing zeros:

    if [ ${FOO%.*} -eq ${BAR%.*} ] && [ ${FOO#*.} \> ${BAR#*.} ] || [ ${FOO%.*} -gt ${BAR%.*} ]; then
      echo "${FOO} > ${BAR}";
    else
      echo "${FOO} <= ${BAR}";
    fi
    

    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).

提交回复
热议问题