How do I get bc(1) to print the leading zero?

How do I get bc(1) to print the leading zero?

I do something like the following in a Makefile:
echo “0.1 + 0.1” | bc

(in the real file the numbers are dynamic, of course)
It prints .2 but I want it to print 0.2.
I would like to do this without resorting to sed but I can’t seem to find how to get bc to print the zero. Or is bc just not able to do this?

Solutions/Answers:

Solution 1:

You can also resort to awk to format:

 echo "0.1 + 0.1" | bc | awk '{printf "%f", $0}'

or with awk itself doing the math:

 echo "0.1 0.1" | awk '{printf "%f", $1 + $2}'

Solution 2:

This might work for you:

echo "x=0.1 + 0.1; if(x<1) print 0; x" | bc

Solution 3:

After a quick look at the source (see bc_out_num(), line 1461), I don’t see an obvious way to make the leading get printed if the integer portion is . Unless I missed something, this behaviour is not dependent on a parameter which can be changed using command-line flag.

Short answer: no, I don’t think there’s a way to make bc print numbers the way you want.

I don’t see anything wrong with using sed if you still want to use bc. The following doesn’t look that ghastly, IMHO:

[me@home]$ echo "0.1 + 0.1" | bc | sed 's/^\./0./'
0.2

If you really want to avoid sed, both eljunior’s and choroba’s suggestions are pretty neat, but they require value-dependent tweaking to avoid trailing zeros. That may or may not be an issue for you.

Solution 4:

I cannot find anything about output format in the documentation. Instead of sed, you can also reach for printf:

printf '%3.1f\n' $(bc<<<0.1+0.1)

Solution 5:

$ bc -l <<< 'x=-1/2; if (length (x) == scale (x) && x != 0) { if (x < 0) print "-",0,-x else print 0,x } else print x'

This one is pure bc. It detects the leading zero by comparing the result of the length with the scale of the expression. It works on both positive and negative number.

Related:  Why using dirname in find command gives dots for each match?

Solution 6:

This one will also handle negative numbers:

echo "0.1 - 0.3" | bc | sed -r 's/^(-?)\./\10./'

References