Using dc

Basic Operations with dc

A primer on using dc(1), the Unix Desk-Calculator.

dc works quite familiarly to ed(1) and it is useful to remember that it is very old.
This, however, does not make it useless!

dc uses reverse-polish notation.

If you would like to divide 168 by 7, you would push 168 and 7 onto the stack, and then push the results back.
This sounds strange but is simple.

You're probably used to:
168/7 [enter]

with dc you would type:
168 [enter]
7 [enter]
/ [enter]
p [enter]

Additionally, you can do this all in one step:
168 7 / p [enter]

If you remember from ed(1), "p" "prints" the current line, so this is simple to remember here.
At any point in time "q" quits, which is also like ed.

Adjust how many points after the decimal you want with "k". Default is 0.
16 3 / p [enter]

5 k
16 3 / p [enter]

5 k
3.14159 1.2 / p [enter]

Rather than entering and exiting dc, you may also use it from a shell (and even with variables):
dc -e "2 k $foo $bar / 100 * p"

For more information and advanced functions (dc can handle some very advanced math), see the manpage and other articles.