Since the following command using bc does not work for numbers in scientific notation, I was wondering about an alternative, e.g. using awk?
sum=$( IFS="+"; bc <<< "${arrValues[*]}" )
sum=$(
awk 'BEGIN {t=0; for (i in ARGV) t+=ARGV[i]; print t}' "${arrValues[@]}"
)
With zsh (in case you don't have to use bash), since it supports floating point numbers internally:
sum=$((${(j[+])arrValues}))
With ksh93:
If you need the kind of precision that bc provides, you could pre-process the numbers so that 12e23 is changed to (12*10^23):
sum=$(
IFS=+
sed 's/\([0-9.]*\)[eE]\([-+]*[0-9]*\)/(\1*10^\2)/g' <<< "${arrValues[*]}" |
bc -l
)
Perl solution:
perl -MList::Util=sum -l -e 'print sum(@ARGV)' -- "${array[@]}"
Or for arbitrary precision:
perl -Mbignum -MList::Util=sum -l -e 'print sum(0, @ARGV)' -- "${array[@]}"
(with a literal 0 added to force the sum to be made with bignums).