Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Floating point arithmetic problem in awk?

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
Can you help.

Platform

HP-UX 11

Scenario.

I am trying to reconcile an invoice file with totals held in the trailer record of the file.

Each invoice line has either a +ve or -ve monetary value in the format 99999999.99. The file contains a trailer record which has a record count (format 99999999) and a total invoice value (99999999999.99)

For example

Invoice A 10.20
Invoice B -5.20
2 5.00


The awk script extracts the trailer values and then sums all the invoice line values in the file.

At the end the calculated values are compared with the trailer to see if the integrity of the file is sound.

Problem
--------

With a simple file like this there is no problem, however with large files, although when the actual and calculated totals are the same (displayed on the screen) they fail the comparison ( == ). I think this is a problem with how real numbers are held internally, and hence tha actaul values in the variables are different when compared, even though they look the same when displayed using printf.

Any ideas.

The script is included below. Note the comparison only considers the invoice total in this example.



function check_invoice_totals()
{
printf "\nFile Totals\n"
printf "-----------\n"
printf " Header Line Count : |%-8s|\n", h_record_count
printf " Actual Line Count : |%8s|\n", a_record_count
printf " Header Invoice Total : |%-14s|\n", h_invoice_tot
printf " Actual Invoice Total : |%14.2f|\n", a_invoice_tot

if (h_invoice_tot == a_invoice_tot)
{
printf "\nINFO : Totals reconcilied successfully\n"
exit 0
}
else
{
printf "\nERROR : Totals do not reconcile. Processing terminated.\n"
exit 1
}
}
BEGIN {
if ( FILENAME == "" )
{
printf "ERROR - PROGRAM CANNOT ACCEPT STANDARD INPUT - PLEASE SPECIFY A FILENAME\n"
exit 1
}
printf "Reading file %s\n", FILENAME

}

# ALL LINES
{

if (substr($0,1,1) == "Z")
{

h_invoice_tot = substr($0,2,14)
h_record_count = substr($0,16,8)
a_record_count++
}

else if (substr($0,1,1) == "B")
{
a_invoice_tot += substr($0,2,11)
a_record_count++
}

} # ALL LINES END

END {
if ( NR == 0 )
{
exit 1
}
else
{
check_invoice_totals()
}
}



 
Your thought is probably correct. I suggest multiplying by 100 the value you are adding to a_invoice_tot and making appropriate changes to the summary code.
Hope this helps. CaKiwi
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top