TextExpander: Inline Calculation

There are many options these days for carrying out ad hoc calculations. Personally I ditched the desktop calculator as soon as I got a personal computer for my day to day work - after all a computer is a very capable calculator. But that left me with various options of how to carry out a calculation. On the Mac there’s the calculator app and following in the steps of launchers like Alfred even Spotlight allows you to carry out quick calculations. If you have a browser open you could even tap into the calculation potential of engines such as Google search of Wolfram-Alpha. However in order to retain my clipboard and tap into something that allowed for some more complex calculations I created a TextExpander snippet to help with this.

The snippet calls a BASH script that begins by prompting the user to enter a calculation. This calculation is passed to a command line utility called bc (bench calculator) which carries out the calculation. The result of the calculation isn’t always formatted in a nice way so the output is held in a variable so we can give it a bit of format based post-processing.

The next step uses printf to set the output to what I find a reasonable size and scale to work with. This is then stripped of any spaces that this might introduce to ensure we only have a numeric value to work with.

Finally the result can still have vestigial zeros at the end so I used a sed (stream editor) instruction (which I cribbed from a thread on linuxmisc.com) to deal with this.

The resulting snippet places the result of the calculation directly into the current application and the clipboard remains untouched.

Label Calculate (BASH)
Description Inserts the result of a calculation.
Abbreviation bccc
Content
#!/bin/bash

#Enter calculation
tecalc=$(echo "%filltext:name=Calculation:width=50%" | bc -l)

#Format for 12 characters & decimals and remove spaces
tecalc=$(printf %12.12f $tecalc | tr -d ' ')

#Remove trailing zeros after the decimal point
tecalc=$(echo $tecalc | sed 's/\(\.[0-9]*[1-9]\)0*$/\1/;s/\.0*$//')

#Output without a newline
echo -n $tecalc

This snippet can be downloaded as part of the Thought Asylum Shell commands snippet group.

Author: Stephen Millard
Tags: | textexpander |

Buy me a coffeeBuy me a coffee



Related posts that you may also like to read