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

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

9

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

$ printf '%.3f\n' "$(echo "scale=3;1/8" | bc)"
0.125
  • More human-readable command. ;-) – Kevin Dong Apr 22 '15 at 14:50
1

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 – user78605 Apr 22 '15 at 14:49
  • @cuonglm so you can, don't edit my answers though please. – user78605 Apr 22 '15 at 14:52
  • @cuonglm Petty downvote, nice! – user78605 Apr 22 '15 at 14:56
  • 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.