Quick tip: The handy command line calculator

[WSL]: Windows Subsystem for Linux — 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-like OSs, including macOS, WSL, and 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 its syntax to the C programming language. A standard math library is available via a 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 standard input. All code is executed as it is read. The only caveat 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, and ibase stands for input base. So in the example, we’re converting 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 you want 20 decimal places, you can use scale to control it:

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

.400

Windows Command Prompt

Command Prompt has a similar tool using the set /a 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 for a wide range of operations:

4 + 5
9

6 * 7
42

[Math]::Sin(50)
-0.262374853703929

[Math]::Max([Math]::Tan(40), [Math]::Cos(40))
-0.666938061652262