“Invalid Arithmetic Operator” doing floating-point

2019-01-09 12:44发布

问题:

Here is my script, its fairly self-explanatory:

d1=0.003
d2=0.0008
d1d2=$((d1 + d2))

mean1=7
mean2=5
meandiff=$((mean1 - mean2))

echo $meandiff
echo $d1d2

But instead of getting my intended output of: 0.0038 2 I am getting the error Invalid Arithmetic Operator, (error token is ".003")?

回答1:

bash does not support floating-point arithmetic. You need to use an external utility like 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))


回答2:

In case you do not need floating point precision, you may simply strip off the decimal part.

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

cuts the integer part of the value. The reason to use cut twice is to parse integer part in case a regional setting may use dots to separate decimals and some others may use commas.