Search code examples
bashshellarithmetic-expressionsbc

In bash how do I divide two variables and output the answer rounded upto 5 decimal digits?


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.


Solution

  • 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.