Sum of all lines in file without roundup with awk

Hi,

I have a file and I want to sum all the numbers in it.

Example of the file:

0.6714359
-3842.59553830551

I used your forum (http://www.unix.com/shell-programming-scripting/74293-how-get-sum-all-lines-file.html\) and found a script, what worked for me:

awk '{a+=$0}END{print a}' output.txt > sum.txt

But the script rounds up my sum and the sum.txt file is like that:

-3841.92

I would like the sum.txt file to be that way:

-3841.92410240551

How to sum up the lines in the file without round-up?

Thank you in advance,

Mario

Use printf instead of print:

printf("%f\n",a)

Regards

For me it only solved half of the problem, because now the output file is like this:

-3841.924102

Better then before :o .

You can change the default of 6 decimals to 11 like this:

printf("%f.11\n",a)

Or you could use Perl:

$
$ cat f2
0.6714359
-3842.59553830551
$
$ awk '{a+=$0}END{print a}' f2
-3841.92
$
$ perl -lne '{chomp;$x+=$_}END{print $x}' f2
-3841.92410240551
$
$

tyler_durden

Thank you both, I will try them as soon as I get to work :slight_smile: .

---------- Post updated at 01:01 PM ---------- Previous update was at 12:49 PM ----------

The ".11" addition only adds it in the end of the number. Like this:

-3841.924102.11

I'll try the pearl advice aswell.

---------- Post updated at 01:43 PM ---------- Previous update was at 01:01 PM ----------

If I use the script:

perl -lne '{chomp;$x+=$_}END{print $x}' f2

alone, then it works, but if I add it to the other row's then it never finishes. My complete sh script is:

grep 'zero point VIBRATIONAL energy' */* > nr001.txt
grep 'total energy' > nr002.txt
awk 'NR==FNR {print $8; next} {print $6}' nr001.txt nr002.txt > nr003.txt
perl -lne '{chomp;$x+=$_}END{print $x}' nr003.txt > nr004.txt

Sorry a typo, should be:

printf("%.11f\n",a)

FWIW -
perl and awk internally represent numbers as doubles. Most implementations have a limit set of DBL_DIG = 15.

Therefore having more than 15 digits in your output string (by forcing it with the format command like printf("%22.18", value) ) is going to give you garbage at some point in the number string.

Thank you, works like a charm :slight_smile: .

---------- Post updated at 02:15 PM ---------- Previous update was at 02:13 PM ----------

I don't think I ever need more then 11, but thank you for the info.