How to get bc to print trailing zeros?
In bc, the solution is to divide by 1:
$ bc -l <<<"scale=8; x=25*20; x"
500
$ bc -l <<<"scale=8; x=25*20; x/1"
500.00000000
So, your script could be like this:
hypothenuse () {
local a b c x y
a=${1}; b=${2}
echo "This is a ${a} and b ${b}"
x=$(echo "scale=8; $a^2/1" | bc -l)
y=$(echo "scale=8; $b^2/1" | 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}"
c=$(echo "scale=8; sqrt($a^2 + $b^2)/1" | bc -l)
echo "This is c ${c}"
}
I strongly suggest that you use $(…)
instead of `…`
.
But even that fails with values of 0.
The best solution is to let the scale of bc be 20 (from bc -l), make all the math required in one call to bc and then format the output as required with printf
. Yes printf
could format floats.
Assuming bash
hypothenuse () { local a b c x y
a=${1:-0} b=${2:-0}
read -d '' x y c < <(
bc -l <<<"a=$a; b=$b; x=a^2; y=b^2; c=sqrt(x+y); x;y;c"
)
printf 'This is a %14.8f and b %14.8f\n' "$a" "$b"
printf 'This is x %14.8f and y %14.8f\n' "$x" "$y"
printf 'This is c %14.8f \n' "$c"
}
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.
Just use awk:
$ cat tst.sh
#!/bin/env bash
hypothenuse() {
awk -v a="$1" -v b="$2" 'BEGIN {
printf "This is a %0.8f and b %0.8f\n", a, b
c = sqrt(a^2 + b^2)
printf "This is c %0.8f\n", c
}'
}
hypothenuse "$@"
$ ./tst.sh 0 0
This is a 0.00000000 and b 0.00000000
This is c 0.00000000
$ ./tst.sh 17.12 23.567
This is a 17.12000000 and b 23.56700000
This is c 29.12898709