16
echo "scale=3;1/8" | bc

shows .125 on the screen. How to show 0.125 if the output result is less than one?

Kevin Dong
  • 1,139
  • 1
  • 9
  • 18

3 Answers3

17

bc can not output zero before decimal point, you can use printf:

$ printf '%.3f\n' "$(echo "scale=3;1/8" | bc)"
0.125
cuonglm
  • 150,973
  • 38
  • 327
  • 406
2

You can pipe into awk

echo "scale=3;1/8" | bc | awk '{printf "%.3f\n", $0}'

or you could just use awk for it all

awk '{printf "%.3f\n", 1/8}' <<< ""

Output

0.125
  • Why should we do `<<< ""`? – Kevin Dong Apr 22 '15 at 14:47
  • @KevinDongNaiJia awk requires an input file to work, this creates and empty `here string`. So basically pretends there is an empty file at the end, otherwise awk will read from stdin.More info [here](http://tldp.org/LDP/abs/html/x17837.html) –  Apr 22 '15 at 14:49
  • 1
    @JID: Not all shell supported here string, you need to specify it for others viewers. Using `BEGIN` block prevent you from that trouble and it's portable. – cuonglm Apr 22 '15 at 14:59
0

Bettering @cuonglm's answer:

a=10.543; b=`printf '%.6f' "$(echo "$a/100" | bc -l)"`; echo $b;

Use "bc -l" to use math library.

Coder
  • 169
  • 1
  • 8