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?

1

3 Answers 3

18

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

$ printf '%.3f\n' "$(echo "scale=3;1/8" | bc)"
0.125
0
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
3
  • 1
    Why should we do <<< ""?
    – Kevin Dong
    Apr 22, 2015 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
    – user78605
    Apr 22, 2015 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, 2015 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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .