To complement karakfa's helpful answer:
In addition to explicit number formatting with printf
and sprintf
, you can also change awk
's default floating-point number formatting, via built-in variable OFMT
.
Note that it does not apply to integers.
OFMT
defaults to %.6g
, which means that any floating-point number is rounded to 6 significant digits and for exponents starting with 7 is represented in scientific notation.
Calculation result 1887436.8
- which has 8 significant digits - is therefore represented as 1.88744e+06
, i.e., in scientific notation with 6 significant digits.
The following example sets OFMT
to %1.f
in order to output all floating-point numbers with 1 decimal place by default:
$ awk -v OFMT='%.1f' 'BEGIN {ram=(1.8 * 1024) * 1024; print ram}'
1887436.8
Note, however, that OFMT
does not apply in the following scenarios:
If the floating-point number is used in a string concatenation:
$ awk -v OFMT='%.1f' 'BEGIN { print "result: " 1 / 3 }'
result: 0.333333
# Workaround: Use `sprintf()` with OFMT
awk -v OFMT='%.1f' 'BEGIN { print "result: " sprintf(OFMT, 1 / 3) }'
result: 0.3
If a literal can be parsed as an integer - even if it looks like a floating-point number:
$ awk -v OFMT='%.1f' 'BEGIN { print 1.000 }'
1
Caveat: There are many subtleties around number conversion and formatting in awk
, not least because of the limited precision of floating-point numbers (which in awk
are always of the ISO C double type).