Skip to content

Instantly share code, notes, and snippets.

@jasonleonhard
Created December 8, 2014 17:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonleonhard/486bf5c1f42b15aefa24 to your computer and use it in GitHub Desktop.
Save jasonleonhard/486bf5c1f42b15aefa24 to your computer and use it in GitHub Desktop.
# 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";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment