Operating System - HP-UX
1748202 Members
3073 Online
108759 Solutions
New Discussion юеВ

Re: Strange output format using sum

 
SOLVED
Go to solution
Wagner Villela
Advisor

Strange output format using sum

Dear friends,

 

I'm doing a column sum using cat+awk+sum (like below) and the final result comes in a strange format.

 

cat lixo_avb | awk '{ sum+=$2} END {print sum}'

 

1.42881e+06

I think it's have some simple solution, but i try some google searches and i can't find any explanation.

 

Some help?

 

Thanks

Wagner
6 REPLIES 6
Matti_Kurkela
Honored Contributor

Re: Strange output format using sum

That's a variant of scientific notation that is actually quite common with computers, called "E notation." It's useful for compact representation of very large or very small numbers.

 

1.42881e+06 means:

 

1.42881 * (10^6) = 1 428 810

 

http://en.wikipedia.org/wiki/Scientific_notation

MK
Patrick Wallek
Honored Contributor

Re: Strange output format using sum

1.42881e+06  means 1.42881 x 10^6 (10 to the 6th power) -- This is standard engineering format and essentially means that you need to move the decimal 6 places to the right.

 

So 1.42881e+06 = 1,428,810

 

Wagner Villela
Advisor

Re: Strange output format using sum

Thanks, dudes.

 

Someone knows any way to force results in a "normal"  output.

 

Change some parameter, etc...

 

edit to say...

 

# echo '1.42881e+06' | awk '{printf "%.0f\n", $0}'

 

# 1428810

 

Well, works fine, but i like to get this result direct from first calc.

Wagner
Dennis Handly
Acclaimed Contributor

Re: Strange output format using awk (scientific notation)

>but I like to get this result direct from first calc.

 

Searching the forum should show you many examples.  From awk(1):

awk '

BEGIN { OFMT = "%.0f" }

{ sum+=$2}

END {print sum}' lixo_avb

 

This also gets rid of the evil cat.  :-)

Matti_Kurkela
Honored Contributor
Solution

Re: Strange output format using sum

The awk function '{printf "%.0f\n", $0}' does not explicitly mean "convert a number from scientific format to regular one", but simply "output this number in this format". Since awk uses standard C library routines, it understands scientific notation automatically. For awk and any other program that uses the standard scanf functions, scientific notation is freely interchangeable with ordinary number notation, unless the programmer has taken deliberate steps to reject input that uses scientific notation.

 

So you'll just have to add the output format specification "%.0f" to your original calculation. To do that, you'll need to switch "print" to "printf", and since printf does not output a newline character unless you explicitly request for it (with \n), you'll have to add that, too.

cat lixo_avb | awk '{ sum+=$2} END {printf "%.0f\n",sum}'

 

 

MK
Wagner Villela
Advisor

Re: Strange output format using sum

You guys rock!

 

Thanks.

Wagner