About mrDoc
Location
Washington DC
Author Biography
—
Computers should be like power tools. You can use them or improve them. Your choice. – Always wear safety glasses.
|
Mac GeekeryGet your geek on. |
When You Need a CalculatorThe neat calendar CLI tip recently posted reminded me of a handy CLI calculator I use frequently. Adding a function to the .bashrc file such as
calc() {
awk "BEGIN {print $* ; }"
}
Gives a simple command line calculator that can handle floats without the limitations of
calc2() {
awk "BEGIN { CONVFMT = \"%.10g\" ; OFMT =\"%.10g\" ; print $* ; }"
}
Handy CLI tools can be easily created using the standard programs on the system. About mrDoc
Location
Author Biography — Computers should be like power tools. You can use them or improve them. Your choice. – Always wear safety glasses. |
|
||||
Why not just use python, it’s just as easy to reach from a terminal.
This tool is something that I found works on all the unix systems I’ve used. There is always some version of awk/gawk/mawk etc. Other languages may not be installed or supported for a variety of reasons.
Python does support a number of calculation formats and one of the first tutorials is to use python as a calculator. My only beef, and it’s a small one, is that you must declare numbers as floats to get a floating point response. If I enter 1/3 into python it will return 0, but if I enter 1/3.0 it will return the standard 0.33333333333. This is a small thing but a bit annoying. But if you want to use python the analogous bash function is
pycalc () { python -c "print $@" }If you want to use perl you can write a little perl script such as
#!/usr/bin/perl print eval(join(' ',@ARGV)).qq{\n};Which is described fully on Ken Schutte’s website. Or you can use a simple alias to perform the same function –
My personal favorite for a ready-built complex command line calculator is calc, an arbitrary precision calculator by Curt Noll. Of course, calc is beyond the scope of the original tip.
Just use `bc -l’? When used with the -l argument, it tells bc to use the mathlib extensions to the POSIX defined standard behavior.
Just read the manual page, eh?
—
unxgeek@unxgeek.us
“Smile,” they said, “it could be worse.”
So I did, and it was.
—
“Smile,” they said, “it could be worse.”
So I did, and it was.
I find bc’s command syntax to be counter intuitive and does not by default perform floating point calculations. The user has to configure that output. Besides the point of this tip was to show something useful and different. Anyone can type “apropos calculator” then fret about the format differences between bc and dc.
What’s wrong with ‘echo $((math expression))’ ?
It’s built into bash, no need for an alias
It doesn’t do floating-point.
That’s strange. zsh behaves pretty well for floating point:
% echo $[4.56 * 1.33]
6.0648
Post new comment