Problem
I have an integer value in C# that needs to be converted to a string, however it must first add zeros:
For Example:
int i = 1;
It has to be 0001 when I convert it to a string.
In C#, I need to know the syntax.
Asked by Pinu
Solution #1
i.ToString(). PadLeft(4, ‘0’) is a function that allows you to pad the left side of your screen. – This is fine, but it doesn’t function with negative values. i.ToString(“0000”); – explicit form i.ToString(“D4″); – short form format specifier $”{i:0000}”; – string interpolation (C# 6.0+)
Answered by Jay
Solution #2
i.ToString("D4");
For further information on format specifiers, go to MSDN.
Answered by Ryan
Solution #3
Here’s an illustration:
int number = 1;
//D4 = pad with 0000
string outputValue = String.Format("{0:D4}", number);
Console.WriteLine(outputValue);//Prints 0001
//OR
outputValue = number.ToString().PadLeft(4, '0');
Console.WriteLine(outputValue);//Prints 0001 as well
Answered by Denys Wessels
Solution #4
You can use:
int x = 1;
x.ToString("0000");
Answered by Yodan Tauber
Solution #5
String interpolation in C# 6.0 style
int i = 1;
var str1 = $"{i:D4}";
var str2 = $"{i:0000}";
Answered by Dr Blowhard
Post is based on https://stackoverflow.com/questions/4325267/c-sharp-convert-int-to-string-with-padding-zeros