I took two variables as input and after dividing them, I want to get the output rounded up to 5 decimal digits. I have tried this way ->
The problem here is that you missed the
printf or any other thing) to provide the data to
$ echo "scale=5; 12/7" | bc 1.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
All together, your snippet should be like:
sum=12 n=7 output=$(echo "scale=5;$sum/$n" | bc) echo "$output"
"scale=5;sum/n"|bc you are just piping an assignment and makes
$ "scale=5;sum/n"|bc bash: 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)" | bc 3.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.