I want to evaluate the expression and display the output correct to 3 decimal places i tried with below code but it is not working help me how to do that in bash.
echo -e "Enter expression to calculate : \c"
read num
let a=num
printf '%f\n' "$a"
Input : 5+50*3/20 + (19*2)/7
Output : 17.000000
Desired Output : 17.929
With bc
:
echo 'scale=3; 5+50*3/20 + (19*2)/7' | bc -l
Output:
17.928
Instead of let a=num
, you could for example:
echo $num | bc
17.92857142857142857142
This is one of the very rare cases where it's acceptable to let a shell variable expand to become part of the body of an awk script:
$ num='5+50*3/20 + (19*2)/7'
$ awk 'BEGIN{print '"$num"'}'
17.9286
$ awk 'BEGIN{printf "%0.3f\n", '"$num"'}'
17.929
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.