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 '17 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 '17 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 '17 at 8:16
up vote 1 down vote accepted

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.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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