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

Leading zeros

Status
Not open for further replies.

SMerrill

Programmer
Jan 19, 2002
145
US
How do I print an integer with leading zeros, i.e. the value 6 printed as 0006 and the value 15 printed as 0015?
 
U can try this:

VAR_1 =sprintf("%.4d",value);

The VAR_1 will contain the desired result.
 
Thanks for the workout ;)
I was getting rusty.

I did it from an input like this:
hjdjnmjd67md8dk349dmcd89f943m39d93m2
8rmdfnmf6e84mdrhf7ri4ner7f894m3nfr78
784jemd7e3i238fnmjie78rnmf7fr83mrmg7

The script looks like this:
function Zeros(str, list) {
while (match(str,/[0-9]+/) != 0) {
list = length(list) < 1 ? substr(str,RSTART,RLENGTH) : list substr(str,RSTART,RLENGTH)
printf &quot;Old string = %s , LIST = %s\n&quot;, str, list
str = substr(str,RSTART + RLENGTH,length(str) - RSTART + RLENGTH)
printf &quot;New string = %s\n&quot;, str
}
list = addZeros(list)
return list
}

function addZeros(str, i,zlist,len) {
i=0
len = length(str)
while (i++ <= len) {
zlist = length(zlist) < 1 ? str : &quot;0&quot; zlist
}
return zlist
}


{
mylist = Zeros($0)
print mylist
}

Try it, it's a lot of fun.
Hopefully this gives you an idea if you need it
for parsing data containing numbers, etc..

Your initial problem can be handled easily:
function addZeroto(str) {
if (length(str) == 1) {
return &quot;000&quot; str
} else if (length(str) == 2) {
return &quot;00&quot; str
} else if (length(str) == 3) {
return &quot;0&quot; str
} else {
return str
}
}
 
Thanks, folks. I ended up using this:

printf(&quot; %03d &quot;,i)

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top