【问题标题】:"Invalid Arithmetic Operator" when doing floating-point math in bash在 bash 中进行浮点数学运算时出现“无效的算术运算符”
【发布时间】:2016-02-25 17:31:25
【问题描述】:

这是我的脚本:

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")?

【问题讨论】:

  • 顺便说一句,如果你从 bash 切换到 ksh93,浮点将是本机可用的。

标签: bash shell unix math


【解决方案1】:

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))

【讨论】:

  • 它只是没有bash 不支持浮点运算。
【解决方案2】:

另一种计算浮点数的方法是使用AWK rounding 能力,例如:

a=502.709672592
b=501.627497268
echo "$a $b" | awk '{print $1 - $2}'

1.08218

【讨论】:

  • 这个答案好多了。
  • 优秀的替代品。
【解决方案3】:

如果您不需要浮点精度,您可以简单地去掉小数部分。

echo $var | cut -d "." -f 1 | cut -d "," -f 1

剪切值的整数部分。使用 cut 两次的原因是为了解析整数部分,以防区域设置可能使用点来分隔小数,而其他一些设置可能使用逗号。

编辑

或者,为了自动化区域设置,可以使用locale

echo $var | cut -d $(locale decimal_point) -f 1

【讨论】:

  • 实际上,您可能应该检查正确的分隔符。如果您只是简单地同时使用两者,那么对于某些(即美国?)标准来说,千位逗号和小数点的逗号可能真的很糟糕。您的脚本会将 1,005.3 削减为 1 而不是 1005。
  • @bufu 当然。实际上可以通过语言环境进行检查。我会更新我的答案。
  • 我不知道有一个locale 可以做到这一点。给我点赞,好先生!
【解决方案4】:

您可以更改您正在使用的外壳。如果您使用 bash shell bash scriptname.sh 执行脚本,请尝试使用 ksh 执行脚本。 Bash 不支持涉及浮点数的算术运算。

【讨论】:

    猜你喜欢
    • 2018-08-17
    • 2019-04-30
    • 1970-01-01
    • 2019-04-16
    • 2014-01-10
    • 1970-01-01
    • 2013-08-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多