[c#] C# convert int to string with padding zeros?

In C# I have an integer value which need to be convereted to string but it needs to add zeros before:

For Example:

int i = 1;

When I convert it to string it needs to become 0001

I need to know the syntax in C#.

This question is related to c# formatting number-formatting

The answer is


.NET has an easy function to do that in the String class. Just use:

.ToString().PadLeft(4, '0')  // that will fill your number with 0 on the left, up to 4 length

int i = 1; 
i.toString().PadLeft(4,'0')  // will return "0001"  

public static string ToLeadZeros(this int strNum, int num)
{
    var str = strNum.ToString();
    return str.PadLeft(str.Length + num, '0');
}

// var i = 1;
// string num = i.ToLeadZeros(5);

int p = 3; // fixed length padding
int n = 55; // number to test

string t = n.ToString("D" + p); // magic     

Console.WriteLine("Hello, world! >> {0}", t);

// outputs: 
// Hello, world! >> 055

i.ToString("0000");

i.ToString("D4");

See MSDN on format specifiers.


Here's a good example:

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

Easy peasy

int i = 1;
i.ToString("0###")

You can use:

int x = 1;
x.ToString("0000");

Simply

int i=123;
string paddedI = i.ToString("D4");

C# 6.0 style string interpolation

int i = 1;
var str1 = $"{i:D4}";
var str2 = $"{i:0000}";

Here I want to pad my number with 4 digit. For instance, if it is 1 then it should show as 0001, if it 11 it should show as 0011.

Below is the code that accomplishes this:

reciptno=1; // Pass only integer.

string formatted = string.Format("{0:0000}", reciptno);

TxtRecNo.Text = formatted; // Output=0001

I implemented this code to generate money receipt number for a PDF file.


To pad int i to match the string length of int x, when both can be negative:

i.ToString().PadLeft((int)Math.Log10(Math.Abs(x < 0 ? x * 10 : x)) + 1, '0')

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to formatting

How to add empty spaces into MD markdown readme on GitHub? VBA: Convert Text to Number How to change indentation in Visual Studio Code? How do you change the formatting options in Visual Studio Code? (Excel) Conditional Formatting based on Adjacent Cell Value 80-characters / right margin line in Sublime Text 3 Format certain floating dataframe columns into percentage in pandas Format JavaScript date as yyyy-mm-dd AngularJS format JSON string output converting multiple columns from character to numeric format in r

Examples related to number-formatting

JavaScript Chart.js - Custom data formatting to display on tooltip Format / Suppress Scientific Notation from Python Pandas Aggregation Results Formula to convert date to number tSQL - Conversion from varchar to numeric works for all but integer Convert string to decimal number with 2 decimal places in Java What is ToString("N0") format? format a number with commas and decimals in C# (asp.net MVC3) SSRS custom number format Format telephone and credit card numbers in AngularJS How to format a number 0..9 to display with 2 digits (it's NOT a date)