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

Awk and basic math fuctions

Status
Not open for further replies.

jkratzer

MIS
Aug 30, 2002
5
US
I have a script that I use to tally up a list of dollar amounts. I am having a problem with it truncating at the 8th digit. If the dollar amount like 123456.78 i get 123456.7 for output.

Code line is:
TOTAL=$(echo $TOTAL $DOL | awk '{print $1+$2}')
Where $DOL is next value to add to total.

Thanks in advance.
 
Hi jkratzer,

Try using printf to specify a float along with the desired number of decimal places.

Example:
TOTAL=$(echo $TOTAL $DOL | awk '{printf("%12.2f\n",$1+$2)}')

Hope this helps,
Grant.
 
That did the trick.......Did not know you could specify decimal places........Thanks for the help.
 
Hi all.
Anyway since this thread refers to it, I had this
which works for money type formatting in awk.

function stupidround(calc, what,x) {
if (x = split(calc,what,".") > 0) {
if (substr(what[2],1,1) == 3) {
return "1"
} else if (substr(what[2],1,1) == 6) {
return "2"
}
} else {
return "3"
}
}

function shortstuf(str) {
return substr(str,1,length(str))".00"
}

function decision(str,m1, x,all) {
all = substr(str,1,m1)
x = (1 + m1)
while (x <= length(str)) {
all = all &quot;,&quot; substr(str,x,3)
x = x + 3
}
#ugly..but you fix it.
all = all&quot;.00&quot; ; sub(/^,/,&quot;&quot;,all)
return all
}


function dim(str, dd) {
if (length(str) <= 3) {
return shortstuf(str)
}

dd = stupidround((length(str) / 3))
return decision(str,dd)
}

BEGIN {
a = dim(ARGV[1])
print a
}



Sample run:
:~ > awk -f awkstuff/money.awk 3783903
3,783,903.00
:~ > awk -f awkstuff/money.awk 37839
37,839.00
:~ > awk -f awkstuff/money.awk 3783
3,783.00
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top