Shell does not give you decimal points. You can multiply ahead to get what you want, though, if you know the result will be 0-99 and not above.
$ printf "0.%02d\n" $(( (a*10000) / b ))
0.99
$
You forgot the multiply by 100 in your bc statement, so your answer is 0.0099, not 0.99. Do that first in your bc statement (i.e. multiply a by 100, not the result of a/b) and it works fine.
Lastly, the way to avoid divide-by-zero errors is to not divide by zero Check your values before you calculate.
Actually, I thought scale & bc are for division and thinking to multiply the result with 100. But I am wrong. Following worked for me:
res=`echo "scale=2; 100 * $a / $b" | bc`
echo $res gave me .99
res=`echo "scale=3; 100 * $a / $b" | bc`
Now echo $res gave me 0.992
How can I avoid script hangup when divide by Zero happens. Validating the variable is the only way? or any otherway in Unix. Actually I need to display 0 when it happens.
---------- Post updated at 10:12 PM ---------- Previous update was at 10:11 PM ----------
Just check. This will turn it into 0/1, which always becomes zero.
[ "$b" -eq 0 ] && a=0; [ "$a" -eq 0 ] && b=1
I'm often sneaky like that. Sorry.
I think 'scale' in bc does pretty much what I did in shell -- multiplies an extra bunch, then cheats the decimal point. bc is smart enough to know when it'd end up 1, though, when my shell statement would do silly things like 0.100