Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bc arithmetic Error

i am trying to solve this bash script which reads an arithmetic expression from user and echoes it to the output screen with round up of 3 decimal places in the end.

sample input

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

sample output

17.929

my code is

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

when there is an input of

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

**my output is **

17.928

which the machine wants it to be

17.929

and due to this i get the solution wrong. any idea ?

like image 274
krrish Avatar asked Dec 07 '14 07:12

krrish


People also ask

What is bc command?

The bc command is an interactive process that provides arbitrary-precision arithmetic. The bc command first reads any input files specified by the File parameter and then reads the standard input.

What is a bc scale?

The BC series scales include the latest technology, and are a drop-in replacement for the legendary PS scale. They offer the same ruggedness, reliability, and ease of operation. BC scales' advanced electronics and graphical display allows greater flexibility and enhanced performance. Mettler Toledo® >> Shipping Scales.

How do I exit bc?

Press ctrl+d will work to exit the program.


1 Answers

The key here is to be sure to use printf with the formatting spec of "%.3f" and printf will take care of doing the rounding as you wish, as long as "scale=4" for bc.

Here's a script that works:

echo -e "please enter math to calculate: \c"
read x
printf "%.3f\n" $(echo "scale=4;$x" | bc -l)

You can get an understanding of what is going on with the above solution, if you run this command at the commandline: echo "scale=4;5+50*3/20 + (19*2)/7" | bc the result will be 17.9285. When that result is provided to printf as an argument, the function takes into account the fourth decimal place and rounds up the value so that the formatted result displays with precisely three decimal places and with a value of 17.929.

Alternatively, this works, too without a pipe by redirecting the here document as input for bc, as follows which avoids creating a sub-shell:

echo -e "please enter math to calculate: \c"
read x
printf "%.3f\n" $(bc -l <<< "scale=4;$x")
like image 178
slevy1 Avatar answered Oct 02 '22 03:10

slevy1