tags:

views:

165

answers:

5

Hi,

in bash I need to compare two float numbers, one which I define in the script and the other read as paramter, for that I do:

   if [[ $aff -gt 0 ]]
    then
            a=b
            echo "xxx "$aff
            #echo $CX $CY $CZ $aff
    fi

but I get the error:

[[: -309.585300: syntax error: invalid arithmetic operator (error token is ".585300")

What is wrong?

Thanks

+1  A: 

Both test (which is usually linked to as [)and the bash-builtin equivalent only support integer numbers.

Joachim Sauer
A: 

bash doesn't do floats.

Marcelo Cantos
+2  A: 

use awk

#!/bin/bash
num1=0.3
num2=0.2
if [ -n "$num1" -a -n "$num2" ];then
  result=$(awk -vn1="$num1" -vn2="$num2" 'BEGIN{print (n1>n2)?1:0 }')
  echo $result
  if [ "$result" -eq 1 ];then
   echo "$num1 greater than $num2"
  fi
fi
ghostdog74
very nice indeed. one last comment, num1 is read from some file and in some cases it is empty, so the comparison gives weird results. how can in back check somehow "if num1 is empty then num1 = 0" ?
Werner
use `-n` to test for non empty string. see `man test` for more info
ghostdog74
A: 

I would use awk for that:

e=2.718281828459045
pi=3.141592653589793
if [ "yes" = "$(echo | awk "($e <= $pi) { print \"yes\"; }")" ]; then
    echo "lessthanorequal"
else
    echo "larger"
fi
ndim
+1  A: 

Using bc instead of awk:

float1='0.43255'
float2='0.801222'

if [[ $(echo "if (${float1} > ${float2}) 1 else 0" | bc) -eq 1 ]]; then
   echo "${float1} > ${float2}"
else
   echo "${float1} <= ${float2}"
fi
yabt