Search code examples
basharithmetic-expressionsbc

Why rounding error in bash?


5+50*3/20 + (19*2)/7 = 17.9285714286
                     = 17.929

I want to get the exact value truncated to 3 decimal places, that is 17.929 by doing the following bash operation.

echo " scale = 3; 5+50*3/20 + (19*2)/7 " | bc

But it gives me the value 17.928.

$ echo " scale = 3; 5+50*3/20 + (10*9)/7 " | bc
17.928

What Can I do??

N.B.: This is a Hackerrank challenge. Even it's not giving correct output in their console.


Solution

  • When you use scale=3 in bc, you're not only specifying the number of decimal places in the output, you're limiting the number of decimal places that bc is using to do its calculations.

    To get the correct output, use printf with bc:

    $ printf '%.3f\n' "$(bc -l <<<'5+50*3/20 + (19*2)/7')"
    17.929
    

    If the expression is inside a variable $var, replace the string in single quotes with "$var".