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?
After a quick look at the source (see
bc_out_num()
, line 1461), I don't see an obvious way to make the leading0
get printed if the integer portion is0
. 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 usebc
. The following doesn't look that ghastly, IMHO: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.Building on potongs answer,
For fractional results:
Note that negative results will not be displayed correctly. Aquarius Power has a solution for that.
echo "$a / $b" | bc -l | sed -e 's/^-\./-0./' -e 's/^\./0./'
This should work for all cases where the results are:
Explanation:
For everything that only starts with
-.
, replace-.
with-0.
For everything that only starts with
.
, replace.
with0.
Probably,
bc
isn't really the best "bench calculator" for the modern age. Other languages will give you more control. Here are working examples that print values in the range (-1.0..+1.0) with a leading zero. These examples usebc
,AWK
, andPython 3
.Note that the Python version is about 10x slower, if that matters.
This one is pure
bc
. It detects the leading zero by comparing the result of thelength
with thescale
of the expression. It works on both positive and negative number.