Math using dc

suggest change

dc is one of the oldest languages on Unix.

It is using the reverse polish notation, which means that you are first stacking numbers, then operations. For example 1+1 is written as 1 1+.

To print an element from the top of the stack use command p

echo '2 3 + p' | dc
5

or

dc <<< '2 3 + p'
5

You can print the top element many times

dc <<< '1 1 + p 2 + p'
2
4

For negative numbers use \_ prefix

dc <<< '_1 p'
-1

You can also use capital letters from A to F for numbers between 10 and 15 and . as a decimal point

dc <<< 'A.4 p'
10.4

dc uses arbitrary precision, which means that the precision is limited only by the available memory. By default the precision is 0 decimal places.

dc <<< '4 3 / p'
1

We can increase the precision with the k command. 2k sets the precision to 2 decimal places:

dc <<< '2k 4 3 / p'
1.33

dc <<< '4k 4 3 / p'
1.3333

You can also use it over multiple lines

dc << EOF
1 1 +
3 *
p
EOF
6

bc is a preprocessor for dc.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents