int value under 10 convert to string two digit number
string strI;
for (int i = 1; i < 100; i++)
strI = i.ToString();
in here, if i = 1
then ToString
yields "1"
But I want to get "01"
or "001"
It looks quite easy, but there's only article about
datetime.ToString("yyyy-MM-dd")`
Solution 1:
i.ToString("00")
or
i.ToString("000")
depending on what you want
Look at the MSDN article on custom numeric format strings for more options: http://msdn.microsoft.com/en-us/library/0c899ak8(VS.71).aspx
Solution 2:
I can't believe nobody suggested this:
int i = 9;
i.ToString("D2"); // Will give you the string "09"
or
i.ToString("D8"); // Will give you the string "00000009"
If you want hexadecimal:
byte b = 255;
b.ToString("X2"); // Will give you the string "FF"
You can even use just "C" to display as currency if you locale currency symbol. See here: https://docs.microsoft.com/en-us/dotnet/api/system.int32.tostring?view=netframework-4.7.2#System_Int32_ToString_System_String_
Solution 3:
The accepted answer is good and fast:
i.ToString("00")
or
i.ToString("000")
If you need more complexity, String.Format is worth a try:
var str1 = "";
var str2 = "";
for (int i = 1; i < 100; i++)
{
str1 = String.Format("{0:00}", i);
str2 = String.Format("{0:000}", i);
}
For the i = 10
case:
str1: "10"
str2: "010"
I use this, for example, to clear the text on particular Label Controls on my form by name:
private void EmptyLabelArray()
{
var fmt = "Label_Row{0:00}_Col{0:00}";
for (var rowIndex = 0; rowIndex < 100; rowIndex++)
{
for (var colIndex = 0; colIndex < 100; colIndex++)
{
var lblName = String.Format(fmt, rowIndex, colIndex);
foreach (var ctrl in this.Controls)
{
var lbl = ctrl as Label;
if ((lbl != null) && (lbl.Name == lblName))
{
lbl.Text = null;
}
}
}
}
}
Solution 4:
ToString can take a format. try:
i.ToString("000");