There are two columns of numbers in a file, the first line like this:

0     0.0       

I want to add the numbers in column 1 to those in column 2, and I want to keep the results floats, not integers. So the result of the first line should be 0.0, and the other lines' results should have .0 even if the sums are integers.

I tried awk:

awk '{printf "%.1g\n", $0=$1+$2}' > sum.txt     

Although I told it to keep one digit after the decimal point by "%.1g\n", it still gives me integer 0.

  • 2
    Use %.1f instead of g. – jordanm Mar 7 at 19:35

I can't see this mentioned in the manual for GNU awk, but e.g. man page for the printf() function in glibc mentions about %g that:

Trailing zeros are removed from the fractional part of the result; a decimal point appears only if it is followed by at least one digit.

Also, there's the # modifier for an "alternate format", which says:

For g and G conversions, trailing zeros are not removed from the result as they would otherwise be.

Also, %g automatically changes to the 1.23e+3 format as necessary, and the precision field (the number after the dot) is "the maximum number of significant digits for g and G conversions" (not digits after the decimal point), so we get:

printf "%#.1g\n", 0                             0.
printf "%#.2g\n", 0                             0.0
printf "%#.2g\n", 12                            12.
printf "%#.2g\n", 1234                          1.2e+03

so while you can force the decimal point to appear, you can't force a trailing zero to appear.

An alternative would be to use %f instead:

printf "%.1f\n", 0                              0.0
printf "%.1f\n", 1234                           1234.0

Or to add the missing zero after the dot as necessary:

a = sprintf("%#.1g", 0); if (substr(a, length(a)) == ".") a = a "0";

Tried with below command

echo "0 0.0"| awk '{sum=$1+$2;printf "%.1f",sum}'


echo "0 0.0"| awk '{sum=$1+$2;printf "%.2f",sum}'


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.