49

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.

Andy Lester
  • 91,102
  • 13
  • 100
  • 152
Manuel Selva
  • 18,554
  • 22
  • 89
  • 134

3 Answers3

64

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.

C2H5OH
  • 5,452
  • 2
  • 27
  • 39
  • 34
    For those who don't often use awk and forget the syntax, here is an example: `echo ""|awk '{printf "%.2f", 1566666666/50}'` – Aaron R. Jul 02 '14 at 21:38
  • 1
    Also note that even if you're summing up integers, [you probably want to use `%f`](http://stackoverflow.com/a/25245025/120999). – Xiong Chiamiov Oct 11 '16 at 00:46
  • 1
    @AaronR. If you don't need `awk` to take any input, you could do `awk 'BEGIN{printf "%.2f", 1566666666/50}'` to use your example. The default selector is `$0`, which is the standard input, & waits for a newline in standard input before running, but `BEGIN` doesn't wait for anything on standard input. Also, to just output a newline, you can just do `echo`, you don't need `echo ""`. – JustinCB Jul 13 '18 at 20:12
  • 1
    You can use eg. `awk '{print sprintf("%.10f", $1/$2), $2}'` – macieksk Jun 10 '20 at 13:40
16

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.

toraritte
  • 6,300
  • 3
  • 46
  • 67
Daweo
  • 31,313
  • 3
  • 12
  • 25
5

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.
Dale C. Anderson
  • 2,280
  • 1
  • 24
  • 24