问题
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 ->
sum=12
n=7
output=$("scale=5;sum/n"|bc)
echo $output
My code isn't showing any output. What can I do??
TestCase:
If sum=3345699 and n=1000000 then (sum/n)=3.345699, it should be changed into 3.34570.
回答1:
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" | 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 sum.
All together, your snippet should be like:
sum=12
n=7
output=$(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"|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.
回答2:
sum and n, these are bash variables. you should add $ to get their values. So, the solution should be:
echo "scale=5;($sum/$n)"|bc
1.71428
回答3:
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.71428
real 0m0.004s
user 0m0.001s
sys 0m0.002s
1.71428
real 0m0.004s
user 0m0.001s
sys 0m0.001s
1.71429
real 0m0.002s
user 0m0.001s
sys 0m0.000s
sh-4.1$
来源:https://stackoverflow.com/questions/39343811/in-bash-how-do-i-divide-two-variables-and-output-the-answer-rounded-upto-5-decim