Re: This Is Not The Problem You're Looking For
- From: "Richard Mueller [MVP]" <rlmueller-nospam@xxxxxxxxxxxxxxxxxxxx>
- Date: Thu, 9 Apr 2009 11:59:21 -0500
"Todd Walton" <tdwalton@xxxxxxxxx> wrote in message
news:09e5e6e0-8c7d-4e7e-926f-1920847155c4@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
I want to print two numbers side by side, and I want to be able to
visually scan down the list and have them lined up. So my list of:
1 10
323 894
541 3001
becomes:
001 0010
323 0894
541 3001
And so? how to write VBScript to pad the number with leading zeroes?
I searched the Internet for a while. There?s lots of talk about ways
to *strip* leading zeroes. There?s a VBScript function (FormatNumber)
that will put one leading zero on if it?s a fraction. Then about
twenty minutes later I found a way of putting leading zeroes on if you
know your number is below a certain length:
Right(?0000? & myNumber, 4)
That creates a four to eight digit number and then chops off and
returns the last four. Giving it ?45? would create ?000045? and then
return the right four digits, ?0045?. That?s good except I don?t know
if my numbers will never be more than four digits or if they might get
to five or six digits.
Suddenly it occurs to me that if I truly don?t know the max length of
my numbers then there?s really no way I could *ever* line them up.
What if my number were suddenly 23 digits long? Or 400? I had been
searching for a general solution, but I suddenly found that... well?
maybe I do know the max length. So I can use the Right() trick.
And then it hits me. Why couldn?t I just print my number and then a
tab?
And thus, I had been working on the wrong problem. Go figure.
-todd
----------
As you imply, there is no "perfect" solution. I never use vbTab because I
get results like:
23 456 52
233333333 456 52
One solution is a function that accepts a parameter indicating the expected
maximum length, and which outputs something to indicate overflow. For
example:
========
strValue1 = "3.45"
strValue2 = "20384"
strValue3 = "2304567"
Wscript.Echo FormatNum(strValue1, 3) & " " & FormatNum(strValue2, 4) & " " &
FormatNum(strValue3, 7)
Function FormatNum(ByVal strValue, ByVal lngMax)
' Check for overflow.
If (Len(CStr(strValue)) > lngMax) Then
FormatNum = String(lngMax, "*")
Exit Function
End If
' Format string with leading zeros up to indicated maximum length.
FormatNum = Right(String(lngMax, "0") & CStr(strValue), lngMax)
End Function
==========
You could also pass numeric values to the function and they would be
converted to strings.
--
Richard Mueller
MVP Directory Services
Hilltop Lab - http://www.rlmueller.net
--
.
- References:
- This Is Not The Problem You're Looking For
- From: Todd Walton
- This Is Not The Problem You're Looking For
- Prev by Date: WScript.dll not working
- Next by Date: Re: Vista - Burn to Cd
- Previous by thread: Re: This Is Not The Problem You're Looking For
- Next by thread: WScript.dll not working
- Index(es):
Relevant Pages
|