I completely agree with jherran that you are not rounding the number, you are trimming it. I would say that the scale probably just does not behave the way you want it, perhaps the way no one wants it to behave.
> x="5+50*3/20 + (19*2)/7" > echo "$x" | bc -l 17.92857142857142857142 > echo "scale = 3; $x" | bc -l 17.928
In addition, due to scale behavior , you round each multiplication / division separately from additions. Let me prove my point with a few examples:
> echo "scale=0; 5/2" | bc -l 2 > echo "scale=0; 5/2 + 7/2" | bc -l 5 > echo "5/2 + 7/2" | bc -l 6.00000000000000000000
However, the scale without any operation also does not work. There is an ugly job:
> echo "scale=0; 5.5" | bc -l 5.5 > echo "scale=0; 5.5/1" | bc -l 5
So things come out of it.
If you want to use the bc scale, do it only for the end result already calculated, and even then beware.
Remember that rounding is the same as truncating a number + half the precision you want.
Let's take an example of rounding to the nearest integer, if you add .5 to the number to be rounded, its integer part will take the next integer value, and truncation will give the desired result. If this number is to be rounded, then adding .5 will not change its integer value, and truncating will give the same result as when nothing was added.
So my solution follows:
> y=$(echo "$x" | bc -l) > echo "scale=3; ($y+0.0005)/1" | bc -l
Again, note that the following does not work (as explained above), so it is very important to break it into two operations:
> echo "scale=3; ($x+0.0005)/1" | bc -l 17.928
source share