How to compare two floating point numbers in Bash?

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

    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=") " %s\n", n1, n2}'
    }
    

    And call it as:

    numCompare 5.65 3.14e-22
    5.65 >= 3.14e-22
    
    numCompare 5.65e-23 3.14e-22
    5.65e-23 < 3.14e-22
    
    numCompare 3.145678 3.145679
    3.145678 < 3.145679
    

提交回复
热议问题