0

I am trying to sum up the numbers and grouping it on a unique key but the sum output is sometimes shows as exponential and some time it shows as integer/floating after rounding off.

Input File

Id|LegNum|Amount1|Amount2|Location
123456|0|238157.5|4280338.799|CL
123456|1|8487.924693|2541829.5|CL
123456|1|14516.47036|31881.6|CL
123789|0|483773.787|10410.78659|CL
456789|0|1321034|1057203.46|NY
456789|1|65802|4913.79677|NY
567890|0|683651.0865|533.617279|IN
567890|0|705864.844|907210|IN

using below awk to sum and group it at first and second column

awk 'BEGIN { FS = "|"; OFS = FS;} NR==1 {print $1,$2,$3,$4,$5;next}{a[$1"|"$2]+=$3;b[$1"|"$2]+=$4;c[$1"|"$2]=$5;}END{for(i in a)print i,a[i],b[i],c[i]}' InputFile.txt >> output.txt 

output.txt shows the sums as exponential OR after rounding off as mentioned below.

Id|LegNum|Amount1|Amount2|Location
123789|0|483774|10410.8|CL
123456|0|238158|4.28034e+06|CL
567890|0|1.38952e+06|907744|IN
123456|1|23004.4|2.57371e+06|CL
456789|0|1321034|1.0572e+06|NY
456789|1|65802|4913.8|NY

But I want the output as floating (without rounding off) if the number is floating and as integer if the number is integer. and definitely don't want the exponential output.

  • You should be able to use printf with %f to print floating point. – unxnut Jul 5 '18 at 9:21
  • but at which place, I should use it. i tried to print using {for(i in a)printf "%f\n" i,a[i],b[i],c[i]} but didn't work as expected – Amit Singh Jul 5 '18 at 9:34
  • @AmitSingh If you are using printf(), you will have to specify the format for each individual parameter. – Kusalananda Jul 5 '18 at 9:42
3

awk uses its OFMT variable as the default printf format for outputting numbers. This is %.6g by default.

You may set this to something like %f or to a more precise format appropriate for your data, or you may want to use printf() instead of print to format the output explicitly.

Example:

$ awk 'BEGIN { print 100000000.10, 2, "hello" }'
1e+08 2 hello

$ awk -vOFMT='%f' 'BEGIN { print 100000000.10, 2, "hello" }'
100000000.100000 2 hello

$ awk -vOFMT='%.2f' 'BEGIN { print 100000000.10, 2, "hello" }'
100000000.10 2 hello

$ awk 'BEGIN { printf("%.2f %d %s\n", 100000000.10, 2, "hello") }'
100000000.10 2 hello

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.