How to compare two floating point numbers ?

How to perform the Arithmetic operations on floating point numbers ?

Showing Answers 1 - 15 of 15 Answers

Amaresh Das

  • Mar 26th, 2007
 

a=3.10
b=-3.10

((c=$a+$b))
if [[ $c -eq 0.00 ]]; then
     echo "$a is equal to $b"
else
     echo "$a is not equal to $b"
fi;


--------------------------------------------
a=3.10
b=-4.00

if [[ $a < $b ]]; then
     echo "$a is less than $b"
else
     echo "$a is greater than $b"
fi;

  Was this answer useful?  Yes

Rahul

  • Mar 28th, 2007
 

You can take this example

x=2.2
$ if [ $x = 2.2 ]
> then
> echo "The numbers compared"
> else
> echo "Not compared"
> fi
The numbers compared

  Was this answer useful?  Yes

Jitu

  • Apr 13th, 2007
 

Hi Amaresh & Rahul,

Could you please recheck your answers..
I think we can't perform addition directly with variables in Shell Scripting.

As Amresh you told.
c=$a+$b rather we may require c=`expr $a + $b`..
Please make me clear if i am wrong..

Hi Rahul as you have written if [ $a -eq 10.5 ]....this condition will always be true while executing...

Actually what i came to know that we can't perform Arithmetic Operation with Floating Point Numbers using "expr"...

Please help me to understand it clearly...

Thanking all of you..
:-)

  Was this answer useful?  Yes

Gaurav

  • Apr 17th, 2007
 

You can make you og 'bc' command to do the arithmatic operations in shell script.
Following script illustrates a sample implimentation

a=1.2
b=3.1
x=$(echo $a+$b|bc)
echo [$x]

Where the arithmatic operation that is desired is marked in bold.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions