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
I want to compare two floating point numbers in a shell script. The following code is not working:
|
||||
|
You could check separately the integer and fractional parts:
As fered says in the comments, it works only if both numbers have fractional parts. 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
output:
|
||||
|
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. |
|||
|
Just use ksh (ksh93 precisely), which supports floating point arithmetics natively:
Edit: Sorry, I missed ksh93 was already suggested. Keeping my answer just to make clear the script posted in the opening question can be used with no change outside the shell switch. |
|||
|