Skip to content

Instantly share code, notes, and snippets.

@leandroh
Created March 17, 2014 18:13
Show Gist options
  • Save leandroh/9605022 to your computer and use it in GitHub Desktop.
Save leandroh/9605022 to your computer and use it in GitHub Desktop.
Just in case anyone is directed to this page, rather than doing some horribly convoluted solution, the following will work on most systems (even ones that dont have bc and perl) - eg many small devices running busybox.
As ahh said - 'awk' is probably your best friend here:
# Return the value of an operation
float_val() {
echo | awk 'END { print '"$1"'; }'
}
Or more usefully:
# Return status code of a comparison
float_test() {
echo | awk 'END { exit ( !( '"$1"')); }'
}
Note you have to invert it as exit(0) = success.
Full Example:
$ cat q.sh
# Float comparison eg float '1.2 > 1.3'
# Return the value of an operation
float_val() {
echo | awk 'END { print '"$1"'; }'
}
# Return status code of a comparison
float_test() {
echo | awk 'END { exit ( !( '"$1"')); }'
}
##########################################
x=1.2
y=1.02
float_test "$x > $y" && echo "$x > $y"
float_test "$x < $y" && echo "$x < $y"
z=`float_val "$x + $y"`
echo "$x + $y = $z"
z=`float_val "$x - $y"`
echo "$x - $y = $z"
Output:
$ sh q.sh
1.2 > 1.02
1.2 + 1.02 = 2.22
1.2 - 1.02 = 0.18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment