How to Compare Floating point / real numbers

Hai,

Can you please guide me, to compare the floating point numbers.

Eg.

If [ $value1 > $value2 ]
then

echo "value1 is grater "

fi

This code is not working properly when i excuted with floating values or real numbers

With zsh:

% [[ 0.3 -gt 0.1 ]]&& echo OK||echo KO
OK
% [[ 0.3 -lt 0.1 ]]&& echo OK||echo KO
KO

HI,

I hope you can do it by awk. For me it is working fine

----------------------------------------------------------------------
# x=3.1; y=3.2; echo "$x $y" | awk '{if ($1 > $2) print $1; else print $2}'
3.2

-----------------------------------------------------------------------
I'm sure you can adapt it to your script

You also can achieve that by using bc

Result=`echo "$Value1 > $Value2" | bc`

if [ $Result -eq 1 ]
then
echo "value1 is greater"
fi

Hi Virmin,

After excuting your code. i am getting a syntax error .

echo "Enter value1"
read value1
echo "Enter value2"
read value2

Result=\`echo "$Value1 > $Value2" | bc \`

if [ $Result -eq 1 ]
then
echo "$value1 is greater"
fi

 Error:
 \-----
 syntax error on line 1, teletype

You are reading value1 and echoing Value1. (And ditto for value2.) value1 and Value1 are 2 different variables.

#!/bin/ksh

a=1.72
b=1.71

if [ "$(echo "if (${a} > ${b}) 1" | bc)" -eq 1 ] ; then
   echo ">"
else
   echo "<"
fi;

as Perderabo said, unix is case sensitive, so value1 and Value1 are totally different variable.
and you have to make sure $Value1 and $Value2 are legal numbers before you use them, or bc will fail.

I corrected the case sensitive, Still i am getting an error

echo "Enter value1"
read value1
echo "Enter value2"
read value2

Result=`echo $value1 > $value2 | bc `

if [ $Result -eq 1 ]
then
echo "$value1 is greater"
fi

ouput
-----

bash-2.03$ ./compare
Enter value1
5.6
Enter value2
3.2
./compare[9]: test: argument expected

Please correct this.

Result=`echo $value1 > $value2 | bc `

Here Im seeing one whitespace in the end of above command.

so please remove that whitespace.

Result=`echo $value1 > $value2 | bc`

Thanks
Sanjay Tripathi

Change

if [ $Result -eq 1 ]

to

if [[ $Result -eq 1 ]]

This will only resolve the error that you are seeing.

Vino, after changing the code..

I am not getting the output .. No errors were display

Er, the input to bc is incorrect. It will give you an error. Use this:

echo "Enter value1"
read value1
echo "Enter value2"
read value2

Result=`echo "if($value1 > $value2) 1" | bc `

if [ $Result -eq 1 ]; then 
   echo "$value1 is greater"
fi

vgersh99 has very similar code in his post... you could have used that as well.

Hi I am getting the error

Here is the output

bash-2.03$ ./file4
Enter value1
4568456
Enter value2
6589546
./file4: [: -eq: unary operator expected

Please correct this code

echo "Enter value1"
read value1
echo "Enter value2"
read value2

Result=`echo "if($value1 > $value2) 1" | bc `

if [ $Result -eq 1 ]; then
echo "$value1 is greater"
fi