C style arithmetic with floating point values in Bash [duplicate]
-
14-07-2021 - |
سؤال
How can I have the right result from this bash script?
#!/bin/bash
echo $(( 1/2 ))
I get 0
as result! So I tried to use these but without success:
$ echo $(( 1/2.0 ))
bash: 1/2.0 : syntax error: invalid arithmetic operator (error token is ".0 ")
$ echo $(( 1.0/2 ))
bash: 1.0/2 : syntax error: invalid arithmetic operator (error token is ".0/2 ")
نصائح أخرى
I once stumbled on a nice piece of code, which is somewhat utilizing suggestion sputnick made, but wraps it around a bash
function:
function float_eval()
{
local stat=0
local result=0.0
if [[ $# -gt 0 ]]; then
result=$(echo "scale=$float_scale; $*" | bc -q 2>/dev/null)
stat=$?
if [[ $stat -eq 0 && -z "$result" ]]; then stat=1; fi
fi
echo $result
return $stat
}
Then, you can use it as:
c=$(float_eval "$a / $b")
لا تنتمي إلى StackOverflow