bc.sh

bc – arbitrary-precision arithmetic language and calculator

This library provides a function to comfortable use bc (basic calculator, aka bench calculator) in a shell script. Thus, it gives you the possibility to do calculations with decimal numbers in shell scripts. Because bc can’t handle exponential format, it comes along with a function to convert from exp to float format.

Dependencies

  • Obviously it dependce on bc, which should be usually installed by standard at nearly every *nix system.

Usage

bc_clc EQUATION [SCALE]
Return the result of the EQUATION with SCALE number of decimal places. The EQUATION should be enclosed by quotation marks.
bc_e2d NUMBER
Convert an exponential number to a decimal number, like 1.345e-2 to 0.01345.

Variables

bc_SCALE
(default: 4) Define the number of decimal places.

Examples

Calculation

To make a simple calculation:

#!/bin/sh
. libinclude.sh
import bc
bc_clc "(45.88*2^4-1)/1.345"

the script will return 545.0408.

By setting SCALE to 6

bc_clc "(45.88*2^4-1)/1.345" 6

or

bc_SCALE=6
bc_clc "(45.88*2^4-1)/1.345"

the script returns 545.040892.

Evaluation

One can also evaluate a statement like

bc_clc "$a < $b"

which will return 1 if true and 0 if false.

exp to float

Simple:

bc_e2d '3.7865e-4'

gives 0.0003786500 ;)

See also

You can also use units.sh to realize calculations with floating point numbers and exponential numbers.