Reputation: 737
I have an integer that I will store in a string according to the following rules:
0
before it. How can I do this in C#?
Upvotes: 3
Views: 1535
Reputation: 91
You can use:
String.Format("{0:D2}", myInt);
The ":D2" tells String.Format to pad the number to at least two digits by prepending zeros. If it's longer than two digits it won't pad anything.
Upvotes: 3
Reputation: 2741
This site is a great reference: http://blog.stevex.net/string-formatting-in-csharp/
For your problem, you can also use this: String.Format("{0:0#}", <yourIntegerVariable>)
Upvotes: 2
Reputation: 30504
You can find information on formatting numbers on MSDN at:
One answer to your question is:
string formatted = myNumber.ToString("00");
Upvotes: 2
Reputation: 18013
int i = 8;
string s = String.Format("{0:00}", i);
00 represents 2 digits 00.00 would represend 2 digits and 2 decimals
Upvotes: 0
Reputation: 887275
If you already have the string, you can write
str = str.PadLeft(2, '0');
Note that you might be looking for
string str = new DateTime(1,1,1, 12,34,56).ToShortTimeString();
This returns 12:34 PM
, and can be customized using format strings.
Upvotes: 1
Reputation: 120917
You can use ToString
with a format string:
var i = 6;
var stringRepresentation = i.ToString("d2");
Upvotes: 7