Float numbers comparision (shell script)

Float numbers comparision (shell script)

Introduction

Since long time I was thinking about How I can compare float numbers in shell script?.

Finally I got answer of this question!! There is no simple & straight forward way to compare float numbers in shell script….

* There are two ways you can solve this. The first is to actually use some sort of more sophisticated mathematical tool like bc to push out the conditional expression, then test its return value to see if your condition was met or not. That’s a bit tricky, particularly since bc can be difficult to use. Another way to use our own logic with beautiful shell commands

Here is my script with will compare float numbers –

root@indianGNU.org:/home/arun# cat float_compare.sh

#! /bin/bash
RESULT=””
################################
#This function will compare LHS > RHS or not
function is_greater_than ()
{
LHS=$1
RHS=$2
min=$((echo $LHS ; echo $RHS) | sort -n | head -1)
if [ “$min” = “$LHS” ]; then
return 1
else
return 0
fi
}
############################
#This function will compare LHS < RHS or not
is_less_than()
{
LHS=$1
RHS=$2
min=$((echo $LHS ; echo $RHS) | sort -n | head -1)
if [ “$min” = “$LHS” ]; then
return 0
else
return 1
fi
echo $min
}

############################
function compare()
{
function=$1
arg1=$2
arg2=$3
#echo -n “$FUNC $ARG1 $ARG2 … ”
################
$function $arg1 $arg2
if [ $? -eq 0 ]; then
#echo TRUE
RESULT=”TRUE”
else
#echo FALSE
RESULT=”FALSE”
fi
}

############################

num1=$1
num2=$2

if [ “$num1” = “$num2” ]; then
echo “$num1 is equal to $num2”
else
## compare num1 > num2
compare is_greater_than $num1 $num2
if [ “$RESULT” = “TRUE” ] ; then
echo “$num1 > $num2”
fi
## compare num1 < num2
compare is_less_than $num1 $num2
if [ “$RESULT” = “TRUE” ] ; then
echo “$num1 < $num2”
fi
fi

root@indianGNU.org:/home/arun#

How to use or Test this script –

root@indianGNU.org:/home/arun# ./float_compare.sh 2 2.33
2 < 2.33
root@indianGNU.org:/home/arun# ./float_compare.sh 2.60  2.33
2.60 > 2.33
root@indianGNU.org:/home/arun# ./float_compare.sh 56.55  65.80
56.55 < 65.80
root@indianGNU.org:/home/arun# ./float_compare.sh 44.80  44.80
44.80  is equal to 44.80
root@indianGNU.org:/home/arun#

Similar Posts:

Be Sociable, Share!

Leave a Reply

Your email address will not be published. Required fields are marked *