Lets say you want to do some math like 3/5 or 1/2, etc (any float point math).

You can do something like this

The problem with that is that we are forking and also opening up a whole new program, this is going to be slow with many calculations. This awesome script (written by dteske) solves this issue all together.

So if you want floating point precision in a shell, usually you would have to use something like awk or other tools. With this awesome tool you dont need anything weird, all tools are provided by the shell. I tested with Bash version 4 and it worked.

Sources: https://raw.githubusercontent.com/FrauBSD/FrauBSD/master/usr.sbin/bsdconfig/share/float.subr  Float.subr needs this shell script: http://svnweb.freebsd.org/base/head/usr.sbin/bsdconfig/share/common.subr?view=co

Installation of float.subr

Download the files: fetch (For FreeBSD)

Wget:

Edit float.subr to load common.subr correctly

Change this:

To this (since common.subr will be in the same dir as float.subr, you can just change it to this – just delete the $BSDCFG_SHARE/  characters):

Try these commands (note I open up a subshell so that float.subrs functions & variables sets dont mess with the local shell):

Example 1: 1/2 which is 0.5

Output should be 0.50

That used subshells, so that the functions which were given by float.subr wouldnt leak to the main shell (they will only be used in the main shell). You can also do this

Or do this (instead of sourcing the script with a dot . <scriptpath>  source it with a source <scriptpath> – there is no difference):

Note that we don’t want to run the script with the regular dot slash notation ./float.subr . This is because running a script with dot slash notation, might run the script in a new subshell of its own, as a child process, and then you wont have access to its functions like f_float. However when you source a script with “source” or dot “.”, the script is ran in the current shell (not as a child process), and then you have access to the functions.

My favorite way to run these (and in the end it really depends on what I want to achived), would be to source the script and run its function/functions in a subshell of its own, like this  (. float.subr; f_float 1 / 2; ) . That way everything in the parenthesis has access to the float.subr functions, but also they dont leak and get left behind in my shell. Its all completely trivial, because if my shell gets “dirty” with functions that I dont like, I can just close out my shell, and log back in and then I will have a clean shell again.

Example 2:

Divide 1 by 17. 1/17. More precision (6 decimal places)

Output should be 0.058823

Thanks dteske!

SIDENOTE: you can move both float.subr and common.subr to a path in your PATH env so that you always have quick access to it

Copy of both scripts (as of March 28th 2016)

float.subr:

common.subr (without the change to the top line):

 

Leave a Reply

Your email address will not be published. Required fields are marked *