passing bash expression to AWK for floating point arithmetic

Viewed 2634

I was trying to do floating point arithmetic in bash, but as floats are not supported, was trying to get the solution using AWK. Below is the issue i am facing:

I see this working fine for me:

code

echo - | awk '{printf("%04.4f \n", (-225.2*7+30*6)/17 + (19^2)/9) }'

output

-42.0301

But my motive is to "read an expression" and compute value correct to 4 decimals, so tried below code inputting same expression (-225.2*7+30*6)/17 + (19^2)/9) and its giving incorrect values(i guess variable is passed as string to awk):

code

read inpt 
echo - | awk -v input=$inpt '{printf("%04.4f \n", input) }'

output

0.0000

Note: Please ignore the space around second + in this example expression, that i can remove using sed or similar methods(with space i get syntactical error in awk while passing variable from bash).

Any help is highly appreciated. Thanks in advance

PS: the bash version in my case is "bash-4.2". I guess its the version of bash preventing me using from many other options.

4 Answers
Related