AWK printf command question

Hi,

I am using below awk code to convert a csv file data into fixed file format.

awk 'BEGIN { FS = ","
             fmt = "%10s%010d%10s%d%1d\n" }
     NR>1  { printf fmt, $1, $2, $3, $4*100, $5 }' /data/mydata.csv > /data/fixed.dat

Data in mydata.csv

XXXXXXXXXX,YYYYYYYY,10/31/2011,10.05,1
AAAAAAAAAA,BBBBBBBB,10/31/2011,10.04,1

For the second row alone, 10.04 is converted into 10.03. i am not sure what is causing this problem. Please clarify.

Thanks,
Bala

---------- Post updated at 12:53 PM ---------- Previous update was at 12:27 PM ----------

Hi Admin,

Please delete this post. I mistaken posted it here in AIX section. Just noticed it. I am not sure how to remove this post.

Floating point numbers don't have infinite precision and don't have boundaries on nice round numbers like you'd expect decimal numbers to. If you want perfect precision without tiny math inaccuracies, manipulate that field with string operations, not math operations. Try stripping out the dot then printing with "%4s".

sub(/\./, "", $4);

Hi Corona688,

Thanks for your reply.

Thanks,
Bala

---------- Post updated at 03:01 PM ---------- Previous update was at 02:58 PM ----------

However, I observed that print command comes with the exact value but not printf. Why there is a difference in both outputs.

---------- Post updated at 03:46 PM ---------- Previous update was at 03:01 PM ----------

Changing the format from decimal to string prevents this conversion.

fmt = "%10s%010d%10s%s%1d\n"