From d97c22df2daaeca6c2cec7f513babb667618f1f0 Mon Sep 17 00:00:00 2001 From: Kurtis Rader Date: Mon, 2 May 2016 20:53:48 -0700 Subject: add floating point output to `math` command This makes it easy for the user to request floating point output with the desired number of digits after the decimal point (not to be confused with significant digits). Note that this is just a thin wrapper so someone can say `math -s3 10 / 3` rather than `math "scale=3; 10 /3"`. Resolves #1643 --- share/functions/math.fish | 57 +++++++++++++++++++++++++++++++---------------- 1 file changed, 38 insertions(+), 19 deletions(-) (limited to 'share/functions') diff --git a/share/functions/math.fish b/share/functions/math.fish index c190ec63..ed638c69 100644 --- a/share/functions/math.fish +++ b/share/functions/math.fish @@ -1,23 +1,42 @@ - function math --description "Perform math calculations in bc" - if count $argv >/dev/null - switch $argv[1] - case -h --h --he --hel --help - __fish_print_help math - return 0 - end + set -l scale 0 # default is integer arithmetic + + if set -q argv[1] + switch $argv[1] + case '-s*' # user wants to specify the scale of the output + set scale (string replace -- '-s' '' $argv[1]) + if not string match -q -r '^\d+$' "$scale" + echo 'Expected an integer to follow -s' >&2 + return 2 # missing argument is an error + end + set -e argv[1] + + case -h --h --he --hel --help + __fish_print_help math + return 0 + end + end + + if not set -q argv[1] + return 2 # no arguments is an error + end + + # Stitch lines together manually. We can't rely on BC_LINE_LENGTH because some systems don't + # have a new enough version of bc. + set -l out (echo "scale=$scale; $argv" | bc | string replace -r '\\\\$' '' | string join '') + switch "$out" + case '' + # No output indicates an error occurred. + return 3 - # Stitch lines together manually - # we can't rely on BC_LINE_LENGTH because some systems don't have a bc version "new" enough - set -l out (echo $argv | bc | string replace -r '\\\\$' '' | string join '') - test -z "$out"; and return 1 - echo $out - switch $out - case 0 - return 1 - end - return 0 - end - return 2 + case 0 + # For historical reasons a zero result translates to a failure status. + echo 0 + return 1 + case '*' + # For historical reasons a non-zero result translates to a success status. + echo $out + return 0 + end end -- cgit v1.2.3