34

I can't figure out why bc tool sometimes ignores the scale option.

Here is an example:

> echo 'scale=2; 2.777 - 1.4744' | bc
1.3026

Expected result is:

1.30

Additional information:

> bash --version
GNU bash, version 2.05b.0(1)-release (x86_64-suse-linux)
Copyright (C) 2002 Free Software Foundation, Inc.
> bc --version
bc 1.06
Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc.
dabest1
  • 2,347
  • 6
  • 25
  • 25

2 Answers2

51

as Carl pointed out, if you check man page, you can find that line. it is about expression explanations. subtraction won't read scale variable. If you want to get the expected result (1.30), you could:

kent$  echo 'scale=2; (2.777 - 1.4744)/1' | bc 
1.30

/ operation will read scale variable.

Kent
  • 189,393
  • 32
  • 233
  • 301
  • 34
    This tool needs to be killed with fire. The insanity. – Michael Renner Jul 09 '13 at 11:52
  • 1
    @AquariusPower Probably the [REPL implementation](http://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop) of a language you know & trust, still not as convenient as bc though, especially when it comes to large numbers. – Michael Renner Jun 04 '14 at 10:02
  • @AquariusPower: Qalculate! is probably the best alternative you can imagine. Anything bigger would be a mathematical suite. It can solve for unknowns, factorize, simplify, do matrix math with complex numbers, use CSV files, deal with units and prefixes easily, has loads of predefined variables, units, functions and many settings, even loads current exchange rates off the Internet if requested, and allows using real Unicode math symbols like e.g. ⋅ for multiplication. Its GUI allows plotting and defining new functions/variables/units too. (Hint, in scripts, use `-t` for terse mode.) – Evi1M4chine Sep 03 '16 at 01:23
5

From the bc(1) man page:

Unless specifically mentioned the scale of the result is the maximum scale of the expressions involved.

1.4744 has scale 4, so that's what happens to your expression.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
  • 5
    And: Division uses the `scale` variable, but not addition, subtraction, or multiplication. They use the scale of the operands. "`expr / expr`: The result of the expression is the quotient of the two expressions. The scale of the result is the value of the variable `scale`." – John Kugelman Dec 20 '12 at 00:13
  • @Carl, thanks for your answer, but it did not make sense when taken out of context from the manual. So I'm choosing Kent's answer as he even provided a workaround. – dabest1 Dec 26 '12 at 17:50