• Uncategorized

About awk : How-can-I-make-awk-not-use-scientific-notation-when-printing-small-values

Question Detail

In the following awk command

awk ‘{sum+=$1; ++n} END {avg=sum/n; print “Avg monitoring time = “avg}’ file.txt

what should I change to remove scientific notation output (very small values displayed as 1.5e-05) ?

I was not able to succeed with the OMFT variable.

Question Answer

You should use the printf AWK statement. That way you can specify padding, precision, etc. In your case, the %f control letter seems the more appropriate.
……………………………………………………

I was not able to succeed with the OMFT variable.

It is actually OFMT (outputformat), so for example:
awk ‘BEGIN{OFMT=”%f”;print 0.000015}’

will output:
0.000015

as opposed to:
awk ‘BEGIN{print 0.000015}’

which output:
1.5e-05

GNU AWK manual says that if you want to be POSIX-compliant it should be floating-point conversion specification.
……………………………………………………
Setting -v OFMT=’%f’ (without having to embed it into my awk statement) worked for me in the case where all I wanted from awk was to sum columns of arbitrary floating point numbers.
As the OP found, awk produces exponential notation with very small numbers,
$ some_accounting_widget | awk ‘{sum+=$0} END{print sum+0}’
8.992e-07 # Not useful to me

Setting OFMT for fixed that, but also rounded too aggressively,
$ some_accounting_widget | awk -v OFMT=’%f’ ‘{sum+=$0} END{print sum+0}’
0.000001 # Oops. Rounded off too much. %f rounds to 6 decimal places by default.

Specifying the number of decimal places got me what I needed,
$ some_accounting_widget | awk -v OFMT=’%.10f’ ‘{sum+=$0} END{print sum+0}’
0.0000008992 # Perfect.

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.