Why do I see a difference in the results for the following code:

read a
printf "%.3f\n" $(bc -l <<< "$a")

RESULT: 17.929 and

read a
echo "scale=3; $a" | bc -l

RESULT: 17.928

My input expression is 5+50*3/20 + (19*2)/7.

They seem to be doing the same thing, but the end result is different. Why?

What change(making use of echo) can I make in the second snippet above to get the same result as the first snippet?

  • Looks like rounding differences between printf and bc. If bc is doing truncation, you could try adding 0.0005 to the result to get round-to-nearest behavior
    – Fox
    Sep 3, 2017 at 17:43
  • 1
    Well the exact result is 17.9285... so basically one solution is just dropping everything after the 8 resulting in 17.928 while the other solution uses rounding rules, which results in 17.929.
    – ADDB
    Sep 3, 2017 at 19:23
  • Is there any change I can make in the echo statement, to have the rounding rules applied to it?
    – 10101010
    Sep 4, 2017 at 8:16

1 Answer 1


This is not a difference between echo and printf but a difference between the number handling of printf and bc.

I guess that printf rounds up the last digit and that bc does not but just puts out the digits as calculated.

You may check this by having both approaches output more digits.

  • 1
    Far as I can see, "scale" truncates (does not round), and it does this on all intermediate results, not just the final output. So representational errors are going to compound very quickly. bc builds on dc, which also behaves like this. Apr 13, 2020 at 16:55

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.