I'm printing an array with 100 columns and I would like all columns to have 2 decimals. I would like to use print $0 and not have to individually specify the format for all columns.
OFMT does seen to work with $0:
echo '0.77767686 0.76555555 0.6667667 0.77878878' |awk '{CONVFMT="%.2g";OFMT="%.2g";print ($0+0);print ($0+0)"";print $0}'
Results:
0.78
0.78
0.77767686 0.76555555 0.6667667 0.77878878
As others have mentioned you need to treat the field as a number to get a conversion. To combine some other ideas you can try:
That will convert every field to a number. You can just convert individual fields with
$7 += 0
and so on. You could get fancier by usingif (match($i, ...))
with some regexp to select only the numbers you want to convert.Why don't you use a
for
loop?Results:
Note that all input is treated as strings until implicitly converted by how it is used.
OFMT
is used when strings are converted to numbers, e.g.:CONVFMT
is used when numbers are converted into strings, e.g.:Output in both cases:
The latter converts
$0
into a number and then concatenates it with the empty string.To achieve this for every column I would suggest using a sensible setting of the input and output record separators:
Note the two conversions, first to a number with
0+$0
then back to a string by concatenating it withRT
.RT
will be set to the matched record separator. Note that this is GNU awk specific, for a more portable solution, use a loop, e.g.:Output in both cases: