Quick tip: The handy command line calculator

Submitted by Robert MacLean on Tue, 06/05/2018 - 09:00

Who needs a GUI to do math when we have options for Unix like (MacOS, Linux etc...), Command Prompt, and PowerShell?

Unix like OSs

Unix OSs, including MacOS, WSL & Linux, include an awesome calculator called BC. From the man page:

bc is a language that supports arbitrary precision numbers with interactive execution of statements. There are some similarities in the syntax to the C programming language. A standard math library is available by command line option. If requested, the math library is defined before processing any files. bc starts by processing code from all the files listed on the command line in the order listed. After all the files have been processed, bc reads from the standard input. All code is executed as it is read.

The only cavet to use, is the file input; you can't just pass in parameters... but you can use echo to pass in the equation. For example:

> echo '1 + 2 + 3 + 4' | bc
> 10

bc can also work with different number bases, for example:

> echo "obase=2; ibase=10; 42" | bc
> 101010

obase stands for output base & ibase stands for input base. So in the example, we are turning 42 (base 10) to binary.

Floating point division is a weirdness with bc. For example, you would expect the answer to be 0.4 below but it is 0:

> echo "2/5" | bc
> 0

The solution is to use the math library switch -l:

> echo "2/5" | bc -l
> .40000000000000000000

and if 20 point position, you can use scale to control it:

> echo "scale=3; 2/5" | bc -l
> .400

Windows Command Prompt

Command prompt has a similar tool with the set command.

>set /a 3+3
6
>set /a (3+3)*3
18
>set /a "203>>3"
25

PowerShell

PowerShell natively supports some basic functionality, but if you want to use more advanced functionality you can use the entire System.Math class to do a lot of functionality.

> 4+5
9
> 6*7
42
> [Math]::Sin(50)
-0,262374853703929
> [Math]::Max([Math]::Tan(40), [Math]::Cos(40))
-0,666938061652262