addition of both positive and negative numbers

Let, I have three numbers

+00123.25
-00256.54
+00489.23

I need to sum up all those three numbers, after storing them in three variables (say var1, var2, var3).

I used both expr and BC, but they didn't work for me.
But, I am not able to sum up them, as I don't have any idea how to take those (+) and (-) sign in account while summing up.

try this:

a=00123.25
b=-00256.54
c=00489.23
echo " $a + $b + $c " | bc
355.94

I posted a simplified version to get the basic idea. Actually, I am reading those values from a file.
The datas are in the following format in a file (say result.txt):

+00000223.20
+00000451.40
+00000451.40
+00000213.20
+00000213.20
-00004135.50
+00001378.50

So, while reading these values in a loop I am not able to sum up the values.

Try this:

sum=$(awk '{s+=$0}END{printf("%.2f\n", s)}' file)
echo $sum
1 Like

Thanks for all your prompt and valuable reponse.
But, in actual scenario, I have to read the data from the file using a while-do-done loop.
Each line I read from the file contains some data, from where I am using grep+cut to read some specific portion from few specific records.And, that specic portion contains those (+)ve and (-)ve values.

So, please let me know is it possible to sum up those numbers in the above scenario?

instead of using while/read and grep/cut, why don't use awk and do it ALL of it natively with one utility...

I ahve to use while/read and grep/cut...because before performing these arithmatic opertaion I need to do a lot more tasks on the source file.
So, if possible please suggest me how to do the arithmatic operation...while using the while/read and grep/cut.

Most likely all other operations could be made easier with awk as well, but if you insist....

#!/bin/ksh
#set -x

sum=0
while read num
do
  num=$(echo $num|sed 's/+//g')
  sum=$(echo "$sum + $num" |bc)
done < myFile
echo $sum

In ksh93 it is easy without external programs:

sum=0
while read val
do
  (( sum+=val ))
done < infile
echo $sum

Or in any Posix compliant shell:

str=0
while read val
do
  str="$str $val"
done < infile
echo $str | bc

It can also be done like this, without a loop:

v=$(cat infile); echo ${v#?} | bc

not all ksh-s provide floating point arithmetics

This doesn't work with Solaris' Bourne shell (/bin/sh)

Correct, that should be ksh93.

It works with any Posix shell (so /usr/xpg4/bin/sh on Solaris).
But this should just work in Bourne shell as well, shouldn't it? Did you try?
-----
edit: Ah, I see you did not mean the loop but the second part: because of the $() .
Then you can use:

v=`cat infile`; echo ${v#?} | bc
paste -sd+ myFile | sed 's/+\([+-]\)/\1/g;s/^+//'|bc

---------- Post updated at 10:01 AM ---------- Previous update was at 10:00 AM ----------

I did try it with Solaris' Bourne (/bin/sh) - 'str' doesn't hold the value outside the loop.

So what? That's an ancient, dessicated stub.

Just sayin'....