In bash how do I divide two variables and output the answer rounded upto 5 decimal digits? [duplicate]
The problem here is that you missed the echo
(or printf
or any other thing) to provide the data to bc
:
$ echo "scale=5; 12/7" | bc1.71428
Also, as noted by cnicutar in comments, you need to use $
to refer to the variables. sum
is a string, $sum
is the value of the variable sum
.
All together, your snippet should be like:
sum=12n=7output=$(echo "scale=5;$sum/$n" | bc)echo "$output"
This returns 1.71428
.
Otherwise, with "scale=5;sum/n"|bc
you are just piping an assignment and makes bc
fail:
$ "scale=5;sum/n"|bcbash: scale=5;sum/n: No such file or directory
You then say that you want to have the result rounded, which does not happen right now:
$ sum=3345699$ n=1000000$ echo "scale=5;($sum/$n)" | bc3.34569
This needs a different approach, since bc
does not round. You can use printf
together with %.Xf
to round to X
decimal numbers, which does:
$ printf "%.5f" "$(echo "scale=10;$sum/$n" | bc)"3.34570
See I give it a big scale, so that then printf
has decimals numbers enough to round properly.
sum
and n
, these are bash variables. you should add $
to get their values. So, the solution should be:
echo "scale=5;($sum/$n)"|bc1.71428
awk 'BEGIN{sum=12;n=7;printf "%0.5f\n", sum/n}'1.71429
In this solution , awk uses printf
to round up decimal to 5 places. If you wish to pass bash variables then use following :
awk -v sum=12 -v n=7 'BEGIN{printf "%0.5f\n", sum/n}' 1.71429
On side notes, awk seem to be good in arithmetic :
sh-4.1$ time echo "scale=5; 12/7" | bc ; time echo "scale=5;($sum/$n)"|bc;time awk 'BEGIN{sum=12;n=7;printf "%0.5f\n", sum/n}'1.71428real 0m0.004suser 0m0.001ssys 0m0.002s1.71428real 0m0.004suser 0m0.001ssys 0m0.001s1.71429real 0m0.002suser 0m0.001ssys 0m0.000ssh-4.1$