15

Ubuntu 14.04.1 LTS

How do I set the default scale for the bc calculator? Each time I run bc I want scale=2 to be the default, I want to limit all calculations to 2 decimal places. I made a file in my home dir called .bc and inside it I put scale=2 on the first line followed by a carriage return.

Permissions on ~/.bc are: -rw-rw-rw-. Is that right?

Then I did set BC_ENV_ARGS=~/.bc; export BC_ENV_ARGS. Then I ran bc, did a test like 8.37843*32.190233, and still got more than 2 decimal places.

The online manual did not provide any examples on doing this, so please don't direct me to there.

Thanks.

EDIT: Ok when I do a test like 78/31 it gives me 2 decimals. But when I do my test above, it gives me more than 2 decimals. Why is that? I always want to show only 2 decimals.

5 Answers 5

18

As muru said, the scale of the result is the maximum scale of the expression involved. but if you want to set the scale for division (want to set the truncation level), place a file .bc in your home (ex. /home/yourid/.bc) and edit it to contain (the file name can be anything)

scale=8  (whatever you want)

Then in your .cshrc file put

setenv BC_ENV_ARGS '/home/yourid/.bc'

Thisway, your default scale is set to 8.

bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'. 
1/3
.33333333
2

quick addendum to what muru said for bash users:

Instead of cshrc, add the following line to your .bashrc in /home/yourname/.bashrc:

export BC_ENV_ARGS=/home/<yourname>/.bc
1
  • You could add export BC_ENV_ARGS="$HOME/.bc" instead to avoid hardcoding the home folder. Plus you might want to move the .bc file into .config which I think is more idiomatic to Ubuntu. Commented Jan 26 at 8:53
2

Put this in your ~/.bashrc, it will give you two decimals:

alias bc="BC_ENV_ARGS=<(echo "scale=2") \bc"

Do a . ~/.bashrc afterwards to load the changes.

This has the benefit of being defined on the fly and you do not need an extra configuration file for it.

1

From man bc (emphasis mine):

Unless  specifically  mentioned  the scale of the result is the maximum
scale of the expressions involved.
....
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.

Reading further, it seems scale is mostly only applicable if division is involved (/, ^ with negative exponents, %, etc.).

Therefore either use some other tool to get it printed the way you want (like printf or awk), or divide by 1:

$ echo '8.37843*32.190233/1' | bc
269.70
1

Invoke bc with the -l option to have scale set to 20 automatically.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .