Joh*_*ith 15 unix math bash shell
这是我的脚本,它相当不言自明:
d1=0.003
d2=0.0008
d1d2=$((d1 + d2))
mean1=7
mean2=5
meandiff=$((mean1 - mean2))
echo $meandiff
echo $d1d2
Run Code Online (Sandbox Code Playgroud)
但不是得到我的预期输出:0.0038 2我收到错误 Invalid Arithmetic Operator, (error token is ".003")?
che*_*ner 35
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))
Run Code Online (Sandbox Code Playgroud)
Noa*_*nos 13
计算浮点数的另一种方法是使用AWK 舍入功能,例如:
a=502.709672592
b=501.627497268
echo "$a $b" | awk '{print $1 - $2}'
1.08218
Run Code Online (Sandbox Code Playgroud)
如果不需要浮点精度,可以简单地去掉小数部分。
echo $var | cut -d "." -f 1 | cut -d "," -f 1
削减值的整数部分。使用 cut 两次的原因是为了解析整数部分,以防区域设置可能使用点来分隔小数,而其他一些设置可能使用逗号。
编辑:
或者,为了自动化区域设置,可以使用locale.
echo $var | cut -d $(locale decimal_point) -f 1
| 归档时间: |
|
| 查看次数: |
31222 次 |
| 最近记录: |