这是我的剧本,它相当不言自明:
d1=0.003
d2=0.0008
d1d2=$((d1 + d2))
mean1=7
mean2=5
meandiff=$((mean1 - mean2))
echo $meandiff
echo $d1d2
但不是得到我的预期输出:
0.0038
2
我收到错误Invalid Arithmetic Operator, (error token is ".003")?
答案 0 :(得分:27)
bash
不支持浮点运算。您需要使用bc
等外部实用程序。
# Like everything else in shell, these are strings, not
# floating-point values
d1=0.003
d2=0.0008
# bc parses its input to perform math
d1d2=$(echo "$d1 + $d2" | bc)
# These, too, are strings (not integers)
mean1=7
mean2=5
# $((...)) is a built-in construct that can parse
# its contents as integers; valid identifiers
# are recursively resolved as variables.
meandiff=$((mean1 - mean2))
答案 1 :(得分:2)
另一种计算浮点数的方法是使用AWK rounding功能,例如:
a=502.709672592
b=501.627497268
echo "$a $b" | awk '{print $1 - $2}'
1.08218
答案 2 :(得分:0)
如果您不需要浮点精度,则可以简单地去除小数部分。
echo $var | cut -d "." -f 1 | cut -d "," -f 1
剪切值的整数部分。两次使用cut的原因是为了分析整数部分,以防区域设置可能使用点分隔小数,而另一些可能使用逗号。
答案 3 :(得分:0)
您可以更改正在使用的外壳。如果要使用bash shell bash scriptname.sh
执行脚本,请尝试使用ksh来执行脚本。 Bash不支持涉及浮点数的算术运算。