views:

99

answers:

5

Hi guys,

I would like to append 0 before a number if it is single digit. ie. it should be 01,02,03... 09, 10, 11, ... and so on

I am using vb.net... how can i do that?

Edit:

It was really nice to c alot of responses...

I am thankful to you all for help. your suggestions worked correctly but i can choose only one correct answer so now in confusion abt which one is the best solution? I am going to choose the one with maximum vote..

A: 
if(number < 10){
  number = Int32.Parse("0" + number.ToString());
}

I guess that was some c# going on :) but you should get the idea.

Undeph
That's going to return an Int32, not a padded string.
jvenema
hmph...Int32.Parse would strip out the leading 0, no?
Piskvor
Ops! Sorry about that ^^ Wasn't thinking straight
Undeph
+1  A: 

Try this:

myNum.ToString().PadLeft(2, "0");
jvenema
You need to set the width as 2 to prefix with zero
Iain Hoult
What does "0-42" mean?
Hans Passant
Good catch Iain
jvenema
+2  A: 

Try the following...

Dim varNumber As Integer = 3
Dim number As String = String.Format("{0:0#}", varNumber)

Hope that helps.

Lance May
1st result for Google: vb.net string format zero. http://idunno.org/archive/2004/14/01/122.aspx
mcandre
@mcandre: I can't visit that link here at work. What am I missing?
Lance May
@Lance: It's a guide to VB.net string formatting, including padding and different format types.
mcandre
+4  A: 
Dim yourNumber as Int32 = 5
yourNumber.ToString("D2") '= "05"
Tim Schmelter
+1 From the docs about the D specifier "This format is supported for integral types only. The number is converted to a string of decimal digits (0-9), prefixed by a minus sign if the number is negative. The precision specifier indicates the minimum number of digits desired in the resulting string. If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier." http://msdn.microsoft.com/en-us/library/aa720653(v=VS.71).aspx
MarkJ
A: 

Old school method from VB6, still works:

Dim yourNumber as Long = 5 
Format(yourNumber, "00") ' = "05" '

... just for old time's sake :). Better to use Tim's answer.

MarkJ