简体   繁体   English

不以bash打印十进制值?

[英]decimal value is not printing in bash?

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. 我想对表达式求值并将输出正确显示为我在以下代码中尝试过的3个小数位,但它无法正常工作,这有助于我在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 : 使用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: 代替let a=num ,您可以例如:

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: 这是极少数情况下的一种情况,可以让shell变量扩展为awk脚本主体的一部分:

$ num='5+50*3/20 + (19*2)/7'

$ awk 'BEGIN{print '"$num"'}'
17.9286

$ awk 'BEGIN{printf "%0.3f\n", '"$num"'}'
17.929

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM