Monday, April 22, 2013

Set scale in (non interactive) scripts with the bc command

If you need to do some kind of math operation in shell scripts you might want to write :
 $ echo "9/2" | bc  
 4  

By default bc truncate the result which is bit annonying...

Using bc -l option gives you a far too precise result :
 $ echo "9/2" | bc -l  
 4.50000000000000000000  

Fortunately, bc comes with the "scale" option to set the scale to whatever presision you wish.

To do it non interactively, you need to specify the scale in the echo before the operation.
For example, to set a precision of 2 digits :
 $ echo -e "scale=2 \n 9/2" | bc  
 4.50  

So the script code would look like :
 val=$(echo -e "scale=2 \n 9/2" | bc)  

No comments:

Post a Comment