Monday, October 19, 2009

Exponential value is awk sum output


In one of my Debian box with mawk 1.3.3 (mawk is an interpreter for the AWK Programming Language), if I try to add the 2nd fields of the following file using awk:

$ cat data.txt
a:99540232
b:89795683
a:08160808
c:0971544
d:99500728
a:12212539898
d:98065599
e:92640031
a:3129013
c:4085555

The output:

$ awk -F ":" '{sum+=$NF} END {print sum}' data.txt
1.27084e+10

So, awk is giving sum output as exponential format as seen above.

To get the above sum output in integer, here is a way:

$ awk -F ":" '{sum+=$NF} END { printf ("%0.0f\n", sum)} ' data.txt
12708429091

But on my Ubuntu 8.04.3 with awk version:

$ awk --version | head -1
GNU Awk 3.1.6

$ awk -F ":" '{sum+=$NF} END {print sum}' data.txt
12708429091

$ awk -F ":" '{sum+=$NF} END { printf ("%d\n", sum)} ' data.txt
12708429091

$ awk -F ":" '{sum+=$NF} END { printf ("%0.0f\n", sum)} ' data.txt
12708429091

1 comment:

Jadu Saikia said...

Subject line would have been

"Exponential value in awk sum output"
bad typo :-(

© Jadu Saikia www.UNIXCL.com