How do I get bc(1) to print the leading zero?
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 0
get printed if the integer portion is 0
. 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:
echo "$a / $b" | bc -l | sed -e 's/^-\./-0./' -e 's/^\./0./'
This should work for all cases where the results are:
- "-.123"
- ".123"
- "-1.23"
- "1.23"
Explanation:
For everything that only starts with
-.
, replace-.
with-0.
For everything that only starts with
.
, replace.
with0.