tonybaldwin | blog

non compos mentis

Quick-n-Dirty floating point math in Bash

leave a comment »

Someone asked me what this:

was all about…having astutely noticed it in the last screenshot I posted.

I often have to quick math on the fly while generating estimates for clients and doing other off the cuff calculations.
Previously, while using openbox or fluxbox, I had a keybinding bring up a calculator and did the math and then killed the calculator with ctrl+q.
But, I’m all about efficiency, and lately have been learning more and more of the powerful tools in bash to do various things, from navigating the file system to handling files and manipulating text. In wmii, I always have at least one bash terminal open (my preferred terminal emulator currently being roxterm).
So, I figured there had to be an efficient means of doing math without bringing up a gui calculator, too, but bash doesn’t like floating point numbers so well.
Now, with expr or echo or let one can do some basic math (ie. expr 220+34, or echo $((220+34))), but not with floating point numbers (with decimal points), which I need.
But bc can do it. One would have to type in something like:
echo ‘5467 * 0.09’ | bc
or
bc -l <<< 5467*0.09
to get the result….
Not really quick-n-dirty…
So, I scripted it:

#!/bin/bash
# do math with bc
echo “Enter your equation:”
read e
echo “The result is:”
bc -l <<< $e

I called the script ‘M’ (for ‘Math’), and stuck it in /usr/local/bin.
Now, I just type
$ M
and I see:

Enter your equation:
(enter equation here)
The result is:
(result appears)
$
all done.
I type 1 letter (two keys, shift+m), and my equation.

tony@deathstar:~$ M
Enter your equation:
3452*0.09
The result is:
310.68
tony@deathstar:~$

./tony

Advertisements

Written by tonybaldwin

February 21, 2010 at 9:14 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: