![在 shell 脚本中对两个浮点数进行减法](https://linux22.com/image/1473323/%E5%9C%A8%20shell%20%E8%84%9A%E6%9C%AC%E4%B8%AD%E5%AF%B9%E4%B8%A4%E4%B8%AA%E6%B5%AE%E7%82%B9%E6%95%B0%E8%BF%9B%E8%A1%8C%E5%87%8F%E6%B3%95.png)
我已经编写了 shell 脚本来减去两个浮点值,例如下面是两个值:
debit_amount=7.853117806000353E7
credit_amount=3223649.619999993
val1=$(printf "%f", "$debit_amount")
val2=$(printf "%f", "$credit_amount")
echo " val1 = " $val1
echo " val2 = " $val2
final=`echo "$val1-$val2" |bc`
输出 :
val1 = 78531178.060004,
val2 = 3223649.620000,
(standard_in) 1: syntax error
我遇到了上述错误。我也尝试了以下命令
final=$(echo "$val1 - $val2"|bc)
echo "$(($val1-$val2))"
echo `expr $val1 - $val2`
但是我仍然收到语法错误。我是否遗漏了什么?
答案1
删除调用中的逗号printf
:
val1=$(printf "%f" "$debit_amount")
val2=$(printf "%f" "$credit_amount")
没有必要用逗号分隔参数。这就是为什么输入bc
看起来像这样:
78531178.060004,-3223649.620000,
无法bc
解释。
顺便提一句:你不应该使用反引号 ( `
) 不再:
final="$(echo "$val1 - $val2" | bc)"