Command-Line Calculator – How to Keep Fractional Values Using BC

bccalculatorcommand line

I just found a good command line calculator program called bc and was satisfied with it until I discovered it rounds off fractional values, thus causing loss in precision.

According to its man page:

All numbers are represented
internally in decimal and
all computation is done in decimal. (This version truncates
results
from divide and multiply operations.)

Could you please suggest an equivalent of bc for Ubuntu Maverick? I need to make advanced command line calculations with variables.

Best Answer

You can set the length of the fractional part with scale=n.

The command echo 'scale=20;752/447' | bc yields:

1.68232662192393736017

Note that even if the number fits within the scale, additional zero's might be appended:

scale=20
1/2
.50000000000000000000

Unfortunately, there is always a rounding issue:

scale=50
1/3*3
.99999999999999999999999999999999999999999999999999
Related Question