Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between printf %.3f and bc rounding behavior

Tags:

bash

printf

bc

Ok so this is a hackerrank problem (https://www.hackerrank.com/challenges/bash-tutorials---arithmetic-operations). Basically, input is an arithmetic expression and I'm supposed to print out formatted answer (3 decimal places). I tried this at first

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

It passed several tests but not the first one.

5+50*3/20 + (19*2)/7 The answer is 17.929 but my code prints out 17.928. I tried this code instead

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

Note: the echo part should be in backticks but I put ' ' to not confuse with block quotes. All tests passed. So what's the difference?

like image 900
tlaminator Avatar asked Oct 02 '14 19:10

tlaminator


2 Answers

The reason that the two differ is that bc always cuts off the numbers instead of rounding them. I. e. echo "scale = 3 ; 8/9" | bc produces 0.888 instead of the correctly rounded 0.889.

Your test case evaluates to 17.928571429, which is rounded to 17.929 with your printf approach, but cut off to 17.928 with the bc approach.

like image 127
cmaster - reinstate monica Avatar answered Sep 28 '22 11:09

cmaster - reinstate monica


I think the problem is scale = 3; part. For example, if you use

      printf "%.3f\n" ` echo  "scale = 3 ; $exp " | bc -l`

You will get 17.928 again. So the answer is you need to set scale at least to 4 and then print it in three digit.

like image 37
CS Pei Avatar answered Sep 28 '22 10:09

CS Pei