How to compare two floating point numbers in Bash?

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

    I used the answers from here and put them in a function, you can use it like this:

    is_first_floating_number_bigger 1.5 1.2
    result="${__FUNCTION_RETURN}"
    

    Once called, echo $result will be 1 in this case, otherwise 0.

    The function:

    is_first_floating_number_bigger () {
        number1="$1"
        number2="$2"
    
        [ ${number1%.*} -eq ${number2%.*} ] && [ ${number1#*.} \> ${number2#*.} ] || [ ${number1%.*} -gt ${number2%.*} ];
        result=$?
        if [ "$result" -eq 0 ]; then result=1; else result=0; fi
    
        __FUNCTION_RETURN="${result}"
    }
    

    Or a version with debug output:

    is_first_floating_number_bigger () {
        number1="$1"
        number2="$2"
    
        echo "... is_first_floating_number_bigger: comparing ${number1} with ${number2} (to check if the first one is bigger)"
    
        [ ${number1%.*} -eq ${number2%.*} ] && [ ${number1#*.} \> ${number2#*.} ] || [ ${number1%.*} -gt ${number2%.*} ];
        result=$?
        if [ "$result" -eq 0 ]; then result=1; else result=0; fi
    
        echo "... is_first_floating_number_bigger: result is: ${result}"
    
        if [ "$result" -eq 0 ]; then
            echo "... is_first_floating_number_bigger: ${number1} is not bigger than ${number2}"
        else
            echo "... is_first_floating_number_bigger: ${number1} is bigger than ${number2}"
        fi
    
        __FUNCTION_RETURN="${result}"
    }
    

    Just save the function in a separated .sh file and include it like this:

    . /path/to/the/new-file.sh
    

提交回复
热议问题