Quick tip: The handy command line calculator

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

*[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 {#commandlinecalculatorunix}

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:

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

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

  1. > echo "obase=2; ibase=10; 42" | bc
  2. > 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:

  1. > echo "2/5" | bc
  2. > 0

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

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

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

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

Windows Command Prompt {#commandlinecalculatorcmd}

Command prompt has a similar tool with the set command.

  1. >set /a 3+3
  2. 6
  3. >set /a (3+3)*3
  4. 18
  5. >set /a "203>>3"
  6. 25

PowerShell {#commandlinecalculatorps}

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.