Permalink
Browse files

.functions: Add `calc`

  • Loading branch information...
1 parent b7389dc commit 3ea3614be94960fa04410c8cafc9ba2e982afb50 @alrra alrra committed with Jan 5, 2013
Showing with 18 additions and 0 deletions.
  1. +18 −0 .functions
View
@@ -1,3 +1,21 @@
+# Simple calculator
+function calc() {
+ local result=""
+ result="$(printf "scale=10;$*\n" | bc --mathlib | tr -d '\\\n')"
+ # └─ default (when `--mathlib` is used) is 20
+ #
+ if [[ "$result" == *.* ]]; then
+ # improve the output for decimal numbers
+ printf "$result" |
+ sed -e 's/^\./0./' `# add "0" for cases like ".5"` \
+ -e 's/^-\./-0./' `# add "0" for cases like "-.5"`\
+ -e 's/0*$//;s/\.$//' # remove trailing zeros
+ else
+ printf "$result"
+ fi
+ printf "\n"
+}
+
# Create a new directory and enter it
function mkd() {
mkdir -p "$@" && cd "$@"

1 comment on commit 3ea3614

Alhadis commented on 3ea3614 May 31, 2016 edited

How's this for a calculator? =)

# Quick calculator: copies result to clipboard after evaluation
calc(){

    # Strip alphabetic characters from input; it's common to copy "180.00 pt" from
    # Adobe Illustrator, or other programs that append units to metric fields.
    local result=$(printf "%s\n" "$*" | perl -pe 's/(\d+|\s+)x(\s+|\d+)/$1*$2/gi; s/[A-Za-z]+/ /g;' | bc -l | tr -d '\\\n')

    # Drop trailing zeroes after the decimal point
    printf %s "$result" | perl -pe 's/\.0+$|(\.\d*?)0+$/$1/g' | pbcopy;

    # Copy to STDERR
    pbpaste;
    printf '\n';
}

Usage: c 150 pt + 130 pt -> displays 280 and copies it to the system clipboard without a trailing newline

Of course, * will glob files, so the function accepts x as an alternative:

c 150 x 3

Nothing that can be done about brackets though, they just have to be quoted:

c '(150 x 150)' or c '(150 * 150)'

Please sign in to comment.