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:
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
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.
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.
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: