How can we compare 2 floating point numbers in SHELL script?
better to compare them as string..
i mean use =(equal to) or !=(not equal to) etc...
ksh93:
if [[ 1.4 -gt 1.39999 ]]; then
echo hallo
fi
if (( 1.4 > 1.39999 )) ; then
echo hallo
fi
man expr, expr evaluates mathematical expressions in sh scripts.
only for integers.
all these codes are for integers. What to do in case of floats?
Hi, what do you mean? Would this ksh93 code be floating pointy enough?
if [[ 1.999999999998 -gt 1.9999999999799 ]] ; then
echo hallo
fi
if [[ 1.999999999998 -lt 1.9999999999799 ]] ; then
echo hallo
fi
What scrutinizer wrote DOES work - but in ksh93.
ghostdog gave you a link to CFA Johnson's post - which gives you an awk answer, or tells you to use bc to multiply to force the values into integers.
Modern shells (ksh88 and bash) do NOT support floating point. Period. And the integers are limited to a range of (this is shown as C constants)
#define LONG_MAX 2147483647
#define LONG_MIN (-2147483647 - 1)
If the number you create by multiplication exceeds LONG_MAX/LONG_MIN you then have to use awk.
End of story in SHELL.
If you don't like this, then write some C/perl/python/ruby code that takes two floating point arguments and compares them
Actually ksh88 is not a modern shell and should be replaced with ksh93. Similar with pdksh, the public domain clone of ksh88.
Another shell that has good floating point support is zsh.
I think it work for floating point but you must use in korn shell only
a=12.345
b=12.354
if [ "$(echo "if (${a} >= ${b}) 1" | bc)" -eq 1 ]
then
echo "more"
else
echo "less"
fi