How to compare two floating point numbers in Bash?

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

    Of course, if you don't need really floating-point arithmetic, just arithmetic on e.g. dollar values where there are always exactly two decimal digits, you might just drop the dot (effectively multiplying by 100) and compare the resulting integers.

    if [[ $((10#${num1/.})) < $((10#${num2/.})) ]]; then
        ...
    

    This obviously requires you to be sure that both values have the same number of decimal places.

提交回复
热议问题