#! /bin/sh
a1=260
a2=9150
echo "$a1 * 100 / $a2" | bc
the output is
2
where it should be
2.8415
why is precision lost although I'm using bc
?
#! /bin/sh
a1=260
a2=9150
echo "$a1 * 100 / $a2" | bc
the output is
2
where it should be
2.8415
why is precision lost although I'm using bc
?
Try this (easy to re-use, you just need to remember to prepends the math expression with scale=N
) :
$ echo "scale=10; $a1 * 100 / $a2" | bc
2.8415300546
As you can see, you can specify the scale length like you want.
See
man bc | less +/^' *scale \(\s*exp
You can load the math library: bc -l
#! /bin/sh
a1=260
a2=9150
echo "$a1 * 100 / $a2" | bc -l
the output is
2.84153005464480874316
You can use awk for better arithmetic:
awk -v a1=260 -v a2=9150 'BEGIN{printf("%.4f\n", (a1 * 100 / a2))}'
output: 2.8415