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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

rounding problem 1

Status
Not open for further replies.

daddymack

MIS
Nov 13, 2001
15
IE
Can anyone shed any light on this, essentially what I am trying to do is read in a column of numbers and print out the number left padded with zeroes(width of 15) and no decimal place i.e

INPUT

0.69 000000000000069
7.1 000000000000710
5 000000000000500

The below script is returning strange results. (a.awk)

{
rec_amt=69.35
d_doc_amt=sprintf("%015d", rec_amt*100)
print &quot;rec_amt is >&quot;rec_amt&quot;< and d_doc_amt is >&quot;d_doc_amt&quot;<&quot;
}

echo 1 | awk -f a.awk

rec_amt is >69.35< and d_doc_amt is >000000000006934<
 

Hello daddymack!

This is because awk's arithmetic is done internally in floating point. Instead %d picture you can use %f picture. See this awk examples (I use awk for DOS and Win):

Code:
awk &quot;BEGIN { printf \&quot;%015d\&quot;, 69.35 * 100 }&quot;
000000000006934

&quot;BEGIN { printf \&quot;%015.0f\&quot;, 69.35 * 100 }&quot;

000000000006935


See also Python's behaviour in this situation:

Code:
>>> print '%015d' % (69.35 * 100)
Traceback (innermost last):
  File &quot;<stdin>&quot;, line 1
TypeError: int argument required

>>> print '%015.0f' % (69.35 * 100)
000000000006935

I suggest you to use %f picture.

Bye!

KP.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top