Simple work around the Bash shell’s inability to compare floating point numbers

Bash can only compare integers (e.g. 0, 1, 2, etc), not floating point numbers (e.g. 0.0, 1.3, 2.99, etc). Searching the web produced all sorts of solutions that involved either too much code or required other programs like "bc". Most servers won't have "bc" installed, so I came up with the following simple solution that seems to work.

My use case is to check if a value is greater than zero, unfortunately the Bash built in "-gt" won't work because "0" in this situation can be reported as "0.00". My solution is to simply check for presence of an integer greater than 0, regardless of location:

1
2
3
4
5
6
value=0
if ( echo "$value" | grep -q [1-9] ); then
  echo yes
else
  echo no
fi
no
1
2
3
4
5
6
value=0.00
if ( echo "$value" | grep -q [1-9] ); then
  echo yes
else
  echo no
fi
no
1
2
3
4
5
6
value=0.099
if ( echo "$value" | grep -q [1-9] ); then
  echo yes
else
  echo no
fi
yes

2 Comments

  • 1. Colin replies at 31st May 2012, 7:12 pm :

    Sorry Alain. I believe that this will only test if the number is 0 (be ie 0 or 0.00).

    What about -ve numbers. I type in -0.99 and I get “yes” as the output.

    My solution is to simply check for presence of an integer greater than 0

    I would at least make a caveat for negative number returns (ok not common if it is a process, but who knows). I believe though that what you want to check for is a 0 result be it 0 or 0.00 or 0.000….[n]0.

  • 2. Alain Kelder replies at 31st May 2012, 7:34 pm :

    Wasn’t a problem for my use case, but if you want negative numbers to evaluate as 0, you could simply do:

    value=-0.99
    if ( echo "$value" | sed /^-/d | grep -q [1-9] ); then
      echo yes
    else
      echo no
    fi
    no

Leave a comment

NOTE: Enclose quotes in <blockquote></blockquote>. Enclose code in <pre lang="LANG"></pre> (where LANG is one of these).