17
bc
1/2
0

5/3
1

10/3
3

When a fraction is entered into bc, the result is truncated to an integer. How can this behavior be avoided, such that the output of a division operation is a real number?

3 Answers 3

19

Try something like scale=2

From the man page:

scale ( expression )

The value of the scale function is the number of digits after the decimal point in the expression.

By default, the scale is 0, so no digits after the decimal are shown.

25

Just invoke bc with the -l argument:

bc -l

Example:

$ bc -l
1/2
.50000000000000000000
5/3
1.66666666666666666666
10/3
3.33333333333333333333
2
  • 1
    This is useful when using bc without entering it, e.g. bc -l <<< 2/4
    – sugab
    Commented May 13, 2022 at 22:55
  • -l is my new favorite flag
    – meh
    Commented Oct 21, 2022 at 14:15
7

Use the scale special variable to define decimal places:

scale=4
1/2
.5000
1
  • Thanks, you both had the right answer, and at essentially the same time.
    – user001
    Commented Jan 12, 2012 at 3:30

You must log in to answer this question.

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