I have a script that reads through a delimited file and adds up the 3rd element in the file for each record. For a majority of the data files, this works fine except for one. I have one data file were there are 193 records in the data file. I am expecting to get 2028219.43 back from the script. Instead, I get an exponental number back which appears to have been rounded up. At first I thought that by using printf I will get the number but if the number has already been rounded, then it's not going to give me back what I am expecting.This is the code that I am using to read the delimited datafile. The data in each record is delimited by an *.:export clm_total=$( awk -F* '{f1+=$3} END {print f1}' datafile.dat)export new_clm_total=$(printf %.2f $clm_total)This is what shows up in the log when I run the script:+ export clm_total=2.02822e+06+ printf %.2f 2.02822e+06+ export new_clm_total=2028220.00+ echo 2028220.00This is a sample of the data file. There are more records, I didn't didn't think it was necessare to display all 193 records:CLM*123456789*4820.9***13:A:1**A*Y*YCLM*123698547*3642.05***13:A:7**A*Y*YCLM*147852369*579.25***13:A:1**A*Y*YCLM*789654123*929.8***13:A:1**A*Y*YWhat I am expecting back is 2028219.43What I am getting back is 2.02822e+06Which then gets formatted as 2028220.00
Shell script and adding large values in a delimited file problem
awk;floating point
Awk performs arithmetic on double-precision floating point numbers. I don't know exactly up to what limit you get exact results for numbers with two decimals, but you're in range. However this could be a problem if the numbers get bigger. If you need to be sure to get exact results, either stick to integers and watch out for overflow, or use bc which performs arbitrary-precision arithmetic.The problem here is that awk is computing the right result, but the default print format is approximative. Use an explicit format when printing out the result.export clm_total=$( awk -F'*' '{f1+=$3} END {printf %.2f\n, f1}' datafile.dat)Alternatively, you can stick to print provided that you change the print format for converting numbers to strings. The default is %.6g which results in the approximation you're seeing.export clm_total=$( awk -F'*' -v CONVFMT='%.2f' '{f1+=$3} END {print f1}' datafile.dat)