summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBen Sima <ben@bsima.me>2022-09-02 09:59:16 -0400
committerBen Sima <ben@bsima.me>2022-09-02 09:59:16 -0400
commite93f27b4b532421e2f95d9bcae4cd2031a4d8d20 (patch)
tree3a4dfe9cf16bc585418efebcab1ef147d86c101e
parent35416ace2f49f05f44b21e163ed0bb544f0ca971 (diff)
add calc script
-rwxr-xr-xcalc16
1 files changed, 16 insertions, 0 deletions
diff --git a/calc b/calc
new file mode 100755
index 0000000..d307962
--- /dev/null
+++ b/calc
@@ -0,0 +1,16 @@
+#!/usr/bin/env bash
+# Simple calculator
+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"