PrintingNumbers

Use printf and a format string instead of print, some examples:

  BEGIN {
    printf "%f", 1000001.10 #prints 1000001.100000
    printf "%.3f", 1000001.10 #prints 1000001.100
    printf "%ld",1000001000000001} #prints 1000001000000001
  }		

For more information about printf see the gnu awk manual

But why does this happen in the first place? awk does something like printf using the format string in the variable OFMT, which contains %.6g by default, when it has to print a number:

  $ echo 12.123123124 | awk '{print $1;print $1+0;OFMT="%.5g";print $1+0;}'
  12.123123124 # here it is printed as a string without conversion
  12.1231      # same as printf "%.6g",$1 ($1+0 is a number)
  12.123       # same as printf "%.5g",$1

Take care that in this example $1 is considered as a string by default, while it would be considered as a number in a boolean expression see truth

There is also another conversion that happens when a number is transformed into a string but not by print, this conversion is controlled by CONVFMT, which is also "%.6g" by default.

  $ echo 12.123123124 | awk '{CONVFMT="%.4g";print ($1+0);print ($1+0) ""}'
  12.1231 # formatted by OFMT ie "%.6g"
  12.12   # it's first converted to a string according to CONVFMT