[HPADM] Summary Adding up a column of number in a file

From: Buddy Mills (ramill@wm.edu)
Date: Wed Dec 01 2004 - 15:05:52 EST


Thanks to Eef Hartman for the syntax, advise and explanation.
 
...used a
  BEGIN { sum = 0 }
and a "printf" instead at the end:
  END { printf "%10.2\n",sum }
so it will print the number with 2 digits after the dot.

BEGIN { sum = 0 }
{ for ( i=1 ; i<=NF ; i=i+1 ) sum = sum + $i}
END { printf "%10.2\n",sum }

used awk's "default number of
significant digits", which seems to be 6 (5 before and 1 after the decimal
point). That is about normal for "single precision floating point" numbers.
Note that the counting IS done in floating point, so rounding errors may occur.

AND thanks to Jeff Lightner for the alternative approach.

#!/bin/ksh
TOTAL=0
for NUMBER in `cat <file>`
do
     TOTAL=`echo $NUMBER + $TOTAL |bc -l`
done
echo $TOTAL
 

Buddy Mills
The College of William and Mary
757-221-2099 ramill@wm.edu
  ----- Original Message -----
  From: Buddy Mills
  To:
  Sent: Wednesday, December 01, 2004 1:01 PM
  Subject: [HPADM] Adding up a column of number in a file

  I need to add up a column of about 1500 number in a file. Each one is a line entry.

  Example
  0076.34
  0003.76
  0048.76
  and so on

  I have used the following two awk scripts.

  { for ( i=1 ; i<=NF ; i=i+1 ) sum = sum + $i}
  END { print sum

  And

  { total += $1 }
  END { print total }

  Both want to round off/drop the last numbers. My file should total 12405.31 and both scripts give me 12405.3

  Any ideas or better ways to do this?

  Thanks

  Buddy Mills
  The College of William and Mary
  757-221-2099 ramill@wm.edu

--
             ---> Please post QUESTIONS and SUMMARIES only!! <---
        To subscribe/unsubscribe to this list, contact majordomo@dutchworks.nl
       Name: hpux-admin@dutchworks.nl     Owner: owner-hpux-admin@dutchworks.nl
 
 Archives:  ftp.dutchworks.nl:/pub/digests/hpux-admin       (FTP, browse only)
            http://www.dutchworks.nl/htbin/hpsysadmin   (Web, browse & search)


This archive was generated by hypermail 2.1.7 : Sat Apr 12 2008 - 11:02:44 EDT