In Python, to print 2 decimal places we will use str. format() with “{:. 2f}” as string and float as a number. Call print and it will print the float with 2 decimal places.
// displaying two-digit day number f = new SimpleDateFormat("dd"); String strDay = f. format(new Date()); System. out. println("Day Number = "+strDay);
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
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_
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;
}
}
}
}
}
ToString can take a format. try:
i.ToString("000");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With