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?
$(...)
instead of`...`
anyhow -- it's the modern POSIX syntax, and less confusing to nest. – Droppingecho "$exp" | bc -l
, notecho $exp | bc -l
; if your expression contained spaces around the*
, you'd have very surprising behavior without the quotes (and even without the spaces, you'd have surprising behavior if your shell had thenullglob
option enabled). – Droppingread a; echo "scale=4; $a" | bc -l | xargs -I {} printf '%.*f\n' 3 {}
– Dutch