bc (Basic Calculator) is a command line utility that offers everything you expect from a simple scientific or financial calculator. It is a language that supports arbitrary precision numbers with interactive execution of statements and it has syntax similar to that of C programming language.

 

It can be used typically as either a mathematical scripting language or as an interactive mathematical shell as explained in this article.

 

If you don’t have bc on your system, you can install it using the package manager for your distribution as shown:

$ sudo apt install bc	#Debian/Ubuntu
$ sudo yum install bc	#RHEL/CentOS
$ sudo dnf install bc	#Fedora 22+

 

To open bc in interactive mode, type the command bc on command prompt and simply start calculating your expressions.

$ bc
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'. 

10 + 5
15

1000 / 5
200

(2 + 4) * 2
12

 

You should note that while bc can work with arbitrary precision, it actually defaults to zero digits after the decimal point, for example the expression 3/5 results to 0 as shown in the following output.

$ bc
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'. 

3 / 5
0

 

You can use the -l flag to sets the default scale (digits after the decimal point) to 20 and defines the standard math library as well. Now run the previous expression once more.

$ bc -l
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'. 

3 / 5
.60000000000000000000

5 / 7
.71428571428571428571

 

Alternatively, you can specify the scale after opening bc as shown.

$ bc
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'. 

scale=0; 8%5
3

scale=1; 8%5
0

scale=20; 8%5
0

scale=20; 8%11
.00000000000000000008

 

You can also use the following command for common shells for instance in bash, ksh, csh, to pass arguments to bc as shown.

$ bc -l <<< "2*6/5"

2.40000000000000000000

 

Let’s look at how to use bc non-interactively, this is also useful for shell scripting purposes.

$ echo '4/2' | bc
$ echo 'scale=3; 5/4' | bc
$ ans=$(echo "scale=3; 4 * 5/2;" | bc)
$ echo $ans

 

To process exactly the POSIX bc language, use the -s flag and to enable warnings for extensions to POSIX bc, use the -w option as shown.

$ bc -s
$ bc -w

 

For more information, view the bc man page.

$ man bc

 

Was this answer helpful? 0 Users Found This Useful (0 Votes)