• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 4025
  • Last Modified:

000 Zero Padding in .vbs

Hi guys. I am looking for a function that puts 3 zero pads in front of numbers.

e.g
Msgbox ZeroPad("9") will output "009"
Msgbox ZeroPad("11") will output "011"
Msgbox ZeroPad("1000") will output "Error"

Thank you
0
New_Alex
Asked:
New_Alex
  • 4
1 Solution
 
Chris BottomleySoftware Quality Lead EngineerCommented:
Try the following:

Chris
Function zeropad(str)
    
    zeropad = (Right("000" & str, 3))

End Function

Open in new window

1
 
X_layerCommented:
Just one correction:
Function zeropad(str)
    if Len(str) <= 3 then
         zeropad = (Right("000" & str, 3))
    else
         zeropad = "Error"
End Function

Open in new window

0
 
Chris BottomleySoftware Quality Lead EngineerCommented:
Adding a little flexibility but more work when calling:

The modified function takes two parameters, first the number to prepend, and secondly how many zeroes to be prepennded, (number of characters to be returned in fact).

Chris
MsgBox ZeroPad(22, 3)

Function ZeroPad(num, charCount)
	ZeroPad = Right(replace(Space(charcount), " ", "0") & num, charCount)
End function

Open in new window

0
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

 
Chris BottomleySoftware Quality Lead EngineerCommented:
Adding checks for non numeric and more than the stipulated number of characters then ...

Chris
MsgBox ZeroPad("0022", 3)

Function ZeroPad(num, charCount)
	If isnumeric(num) Then
		If Len(num) > charcount Then
			ZeroPad = "Error"
		Else
			ZeroPad = Right(replace(Space(charcount), " ", "0") & num, charCount)
		End if
	Else
		ZeroPad = "Error"
	End if
End Function

Open in new window

0
 
Chris BottomleySoftware Quality Lead EngineerCommented:
Basically the same but making the three character limit hard so that the call is 'easier' but keeping the simplicity to change the length of the string easily at the code level (within the function)

Chris
MsgBox ZeroPad("a2")

Function ZeroPad(num)
Const charCount = 3

	If isnumeric(num) Then
		If Len(num) > charcount Then
			ZeroPad = "Error"
		Else
			ZeroPad = Right(replace(Space(charcount), " ", "0") & num, charCount)
		End if
	Else
		ZeroPad = "Error"
	End If

End Function

Open in new window

0
 
New_AlexAuthor Commented:
Thank you sir
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now