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!

Padding A String With Zeroes

Status
Not open for further replies.

tbohon

Programmer
Apr 20, 2000
293
US
I have a numeric value which is used each time the program runs to automatically number items in a database file. I can easily convert from string to numeric using val() and from numeric back to string with str$(). However, I need the resulting string to always have exactly 6 characters, e.g., 000742 and not just 742.

I did a simple while-wend loop after converting back to the string:

while len(n$) < 7
n$=&quot;0&quot;+n$
wend

This results in, for example, n$ = 00 742

I've done this before (many years ago) so I know it's possible - just can't remember how I solved this.

Thanks in advance for the assist.

Tom
 
n$ = STRING$(6-LEN(n$), &quot;0&quot;) + n$

or

num$ = STRING$(6, &quot;0&quot;)
MID$(NUM$, 6 - LEN(n$) + 1, LEN(n$)) = n$

MID$ allows you to set string characters or read certain characters. MID$(String, StartIndex, NumChars) it can be used as an assignment or as a value returning function. Or you could use STRING$ to make a zero string of 6-LEN$(n$) and stick them both together.




 
Or,
while len(n$) < 7
n$=&quot;0&quot;+LTRIM$(n$)
wend

n$=right$(n$,7) 'just to be sure

In Qbasic/QuickBasic and others when you convert a numeric
to a string it typically puts a space character as the first character.


 
Thanks - tried both, all works.

Shows what happens to the gray matter when you're out of programming and doing 'management stuff' for several years.

Tom
 
Here's the approach I take, by the way. It is conceptually a bit cleaner than repeatedly adding to a string.
[tt]
padded$ = RIGHT$(&quot;000000&quot; + LTRIM$(STR$(number%)), 7)
[/tt]
Of course this only works with positive numbers.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top