I want to compare two floating point numbers in a shell script. The following code is not working:
#!/bin/bash min=12.45 val=10.35 if (( $val < $min )) ; then min=$val fi echo $min
You could check separately the integer and fractional parts:
As fered says in the comments, it works only if both numbers have fractional parts and both fractional parts have the same number of digits. Here's a version that works for integer or fractional and any bash operator:
Bash does not understand floating point arithmetic. It treats numbers containing a decimal point as strings.
Use awk or bc instead.
If you intend to do a lot of math operations, it's probably better to rely on python or perl.
You can use package num-utils for simple manipulations...
For more serious maths, see this link... It describes several options, eg.
An example of
Here is a
For simple calculations on floating point numbers (+-*/ and comparisons), you can use awk.
Or, if you have ksh93 or zsh (not bash), you can use your shell's built-in arithmetic, which supports floating point numbers.
For more advanced floating point calculations, look up bc. It actually works on arbitrary-precision fixpoint numbers.
Use numeric sort
These examples are finding the minimum:
It works with pretty general notation of floating point numbers, like with the E-Notation
Can compare to infinity
The floating point standard, IEEE754, defines some special values. For these comparisons, the interesting ones are
To find the maximum use
To implement the
Edit: Sorry, I missed
Edit2: Note that
A more robust solution is to set the locale at the beginning of the script to make sure it will work regardless of the user's locale:
That uses the
If the top entry was less than the second to top it pushes the contents of
Else it does nothing and the stack still looks like:
Then it just
So for your problem:
Why not to use old, good
For true expressions, expr exit code is 0, with string '1' sent to stdout. Reverse for false expressions.
I've checked this with GNU and FreeBSD 8 expr.
To check if two (possibly fractional) numbers are in order,
However, if you actually want to keep a minimum value updated, then you don't need an