18
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,169

3 Answers3

18

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

$ printf '%.3f\n' "$(echo "scale=3;1/8" | bc)"
0.125
cuonglm
  • 153,898
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
  • 1
    Why should we do <<< ""? – Kevin Dong Apr 22 '15 at 14:47
  • 1
    @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 –  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
1

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
  • 179