Naveen Reddy CH
Naveen Reddy CH

Reputation: 849

How to compare to decimal values in if statement?

I want to compare two decimal values in if statement, but it is not giving as expected. Suppose,I have one decimal value in $value variable. Then if [ $value -eq 0.00 ] is not working eventhough $value is 0.00.

Please help in this regard. Thanks in advance!

Upvotes: 0

Views: 4087

Answers (1)

aymericbeaumet
aymericbeaumet

Reputation: 7342

Some shells support float, others don't:

  • Bash doesn't support float values.
  • Zsh does support float values.

In any case, the -eq operator exists to perform comparison between integers, not float (even in Zsh).

I don't know which shell you're using, but there is two solutions. Choose the one you prefer: avoid an external dependency or manipulate real floats.

Consider floats as strings

This way, you can compare string directly with the = operator (the string equality operator).

A=1.1
B=1.1
if [ "$A" = "$B" ] ; then
    echo 'Yeah!'
fi

Use bc to perform real float operations

bc is a calculator which can be called (as any other program) in a shell script expression.

A=1.1
B=1.1
if [ "$(bc <<< "$A - $B")" = 0 ] ; then
    echo 'Yeah!'
fi

Upvotes: 2

Related Questions