BC Command – How to Print Trailing Zeros in Shell Script

arithmeticawkbcshell-scripttext formatting

I read topics about how to get bc to print the first zero, but that is not exactly what I want. I want more…

I want a function that returns floating point numbers with eight decimal digits. I am open to any solutions, using awk or whatever to be fair.
An example will illustrate what I mean:

hypothenuse () {
        local a=${1}
        local b=${2}
        echo "This is a ${a} and b ${b}"
        local x=`echo "scale=8; $a^2" | bc -l`
        local y=`echo "scale=8; $b^2" | bc -l`
        echo "This is x ${x} and y ${y}"
#       local sum=`awk -v k=$x -v k=$y 'BEGIN {print (k + l)}'`
#       echo "This is sum ${sum}"
        local c=`echo "scale=8; sqrt($a^2 + $b^2)" | bc -l`
        echo "This is c ${c}"
}

Sometime, a and b are 0.00000000, and I need to keep all these 0s when c is returned. Currently, when this happens, this code give back the following output:

This is a 0.00000000 and b 0.00000000
This is x 0 and y 0
This is c 0

And I would like it to print

This is a 0.00000000 and b 0.00000000
This is x 0.00000000 and y 0.00000000
This is c 0.00000000

Help will be much appreciated!

Best Answer

You can externalize formatting this way, using printf:

printf "%0.8f" ${x}

Example:

x=3
printf "%0.8f\n" ${x}
3.00000000

Note: printf output depends on your locale settings.

Related Question