How to compare two floating point numbers in Bash?

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

    I was posting this as an answer to https://stackoverflow.com/a/56415379/1745001 when it got closed as a dup of this question so here it is as it applies here too:

    For simplicity and clarity just use awk for the calculations as it's a standard UNIX tool and so just as likely to be present as bc and much easier to work with syntactically.

    For this question:

    $ cat tst.sh
    #!/bin/bash
    
    num1=3.17648e-22
    num2=1.5
    
    awk -v num1="$num1" -v num2="$num2" '
    BEGIN {
        print "num1", (num1 < num2 ? "<" : ">="), "num2"
    }
    '
    
    $ ./tst.sh
    num1 < num2
    

    and for that other question that was closed as a dup of this one:

    $ cat tst.sh
    #!/bin/bash
    
    read -p "Operator: " operator
    read -p "First number: " ch1
    read -p "Second number: " ch2
    
    awk -v ch1="$ch1" -v ch2="$ch2" -v op="$operator" '
    BEGIN {
        if ( ( op == "/" ) && ( ch2 == 0 ) ) {
            print "Nope..."
        }
        else {
            print ch1 '"$operator"' ch2
        }
    }
    '
    
    $ ./tst.sh
    Operator: /
    First number: 4.5
    Second number: 2
    2.25
    
    $ ./tst.sh
    Operator: /
    First number: 4.5
    Second number: 0
    Nope...
    

提交回复
热议问题