TrumanWong

bc

Arithmetic operations precision arithmetic tools

Supplementary instructions

bc command is a calculator language that supports arbitrary precision interactive execution. Bash has built-in support for four integer arithmetic operations, but it does not support floating point operations. The bc command can easily perform floating point operations, and of course integer operations are no longer a problem.

grammar

bc(option)(parameter)

Options

-i: Force into interactive mode;
-l: Define the standard math library used;
-w: Gives a warning message for the POSIX bc extension;
-q: Do not print normal GNU bc environment information;
-v: Display command version information;
-h: Display help information for the command.

Parameters

File: Specify the file containing the calculation task.

Example

Arithmetic operations advanced operations bc command which can perform floating point operations and some advanced functions:

echo "1.212*3" | bc
3.636

Set decimal precision (numeric range)

echo "scale=2;3/8" | bc
0.37

The parameter scale=2 sets the decimal place of the bc output result to 2 digits.

Base conversion

#!/bin/bash
abc=192
echo "obase=2;$abc" | bc

The execution result is: 11000000, which is to use bc to convert decimal to binary.

#!/bin/bash
abc=11000000
echo "obase=10;ibase=2;$abc" | bc

The execution result is: 192, which is using bc to convert binary to decimal.

Compute squares and square roots:

echo "10^10" | bc
echo "sqrt(100)" | bc