From b816cd6d50af9b9d88b218fb98d671a62d57541f Mon Sep 17 00:00:00 2001 From: Kurtis Rader Date: Wed, 23 Aug 2017 17:31:04 -0700 Subject: [PATCH] Change how `math` rounds integer results We need our `math` builtin to behave like `bc` with respect to rounding floating point values to integer to avoid breaking to many existing uses. So when scale is zero round down to the nearest integer. Another change for #3157. --- doc_src/math.txt | 2 +- src/builtin_math.cpp | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/doc_src/math.txt b/doc_src/math.txt index a47d005ec224..1113ef7da14b 100644 --- a/doc_src/math.txt +++ b/doc_src/math.txt @@ -15,7 +15,7 @@ The `math` command can evaluate multiple expressions separated by commas. The re The following options are available: -- `-sN` or `--scale=N` sets the scale of the result. `N` must be an integer and defaults to zero (rounded to the nearest integer). +- `-sN` or `--scale=N` sets the scale of the result. `N` must be an integer and defaults to zero. A scale of zero causes results to be rounded down to the nearest integer. So `3/2` returns `1` rather than `2` which `1.5` would normally round to. This is for compatibility with `bc` which was the basis for this command prior to fish 3.0.0. Scale values greater than zero causes the result to be rounded using the usual rules to the specified number of decimal places. \subsection return-values Return Values diff --git a/src/builtin_math.cpp b/src/builtin_math.cpp index f69ba163dd5e..cae45ba5861b 100644 --- a/src/builtin_math.cpp +++ b/src/builtin_math.cpp @@ -133,7 +133,11 @@ static int evaluate_expression(wchar_t *cmd, parser_t &parser, io_streams_t &str int nNum; mu::value_type *v = p.Eval(nNum); for (int i = 0; i < nNum; ++i) { - streams.out.append_format(L"%.*lf\n", opts.scale, v[i]); + if (opts.scale == 0) { + streams.out.append_format(L"%ld\n", static_cast(v[i])); + } else { + streams.out.append_format(L"%.*lf\n", opts.scale, v[i]); + } } return STATUS_CMD_OK;