5

I am new to BASH and learnt that both printf and echo write to the standard output. But, I came through the following example which reads an expression from input and computes the result to accuracy of 3 decimal places:

read exp
printf "%.3f\n" "$(echo $exp | bc -l)"

I don't get why echo is passed here as an argument in the the printf statement. Is there any other way to represent the statement using only echo?

Radu Rădeanu
  • 169,590
coder_r
  • 53

2 Answers2

4

After read exp, you can use echo as follow:

$ echo "scale=3; $exp/1" | bc
9.456

But note that this command does not require echo:

$ bc <<< "scale=3; $exp/1"
9.456

EDIT: in order to get a rounded result you have to use the printf bash builtin as bc can't round values.

The following command works as expected:

 echo "scale=4; $exp" | bc | xargs printf "%.3f\n"
  • Your solution works right but the value is not precise to 3 decimal places .ex: 5+503/20 + (192)/7 your solution gives 17.928 but the answer is 17.929 – coder_r Oct 29 '14 at 13:32
  • 1
    @coder_r: To get rounded values, you have to have the bash printf builtin as bc alone won't round results – Sylvain Pineau Oct 29 '14 at 16:35
2

Here is a solution using only echo:

  • if you are using a decimal point (.) in your rational number:

    $ read exp
    123.4567
    $ int=${exp%%.*}
    $ rat=${exp##*.}
    $ echo $int.${rat:0:3}
    123.456
    
  • if you are using a decimal comma (,) in your rational number (as I use and most part of continental Europe):

    $ read exp
    123,4567
    $ int=${exp%%,*}
    $ rat=${exp##*,}
    $ echo $int,${rat:0:3}
    123,456
    

For more info see Advanced Bash-Scripting Guide: Manipulating Strings.

Radu Rădeanu
  • 169,590