bash bcmath functions

Posted by Gordon on Stack Overflow See other posts from Stack Overflow or by Gordon
Published on 2010-04-28T04:54:01Z Indexed on 2010/04/28 6:03 UTC
Read the original article Hit count: 356

Filed under:
|

I have two functions for GNU bc in a Bash script.

BC_CEIL="define ceil(x) { if (x>0) { if (x%1>0) return x+(1-(x%1)) else return x } else return -1*floor(-1*x) }\n"
BC_FLOOR="define floor(x) { if (x>0) return x-(x%1) else return -1*ceil(-1*x) }\n"
echo -e "scale=2"$BC_CEIL$BC_FLOOR"ceil(2.5)" | bc

Both functions work fine in interactive bc. bc does not seem to allow multiple functions on one line separated by ; though, so I have to echo -n | bc with newlines at the end of each function. The above output is 2.5, not the expected 3.0 that I get if I type it into bc -i myself. It seems that bash calls bc for each line of echo output, rather than echo'ing it all to a single instance. Is there any workaround for this?

© Stack Overflow or respective owner

Related posts about bash

Related posts about bcmath