C# convert int to string with padding zeros?
Asked Answered
P

15

548

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#.

Poindexter answered 1/12, 2010 at 14:18 Comment(1)
This may help you - How to: Pad a Number with Leading Zeros. Good luckHereinafter
F
911

i.ToString().PadLeft(4, '0') - okay, but doesn't work for negative numbers
i.ToString("0000"); - explicit form
i.ToString("D4"); - short form format specifier
$"{i:0000}"; - string interpolation (C# 6.0+)

Flavescent answered 1/12, 2010 at 14:21 Comment(1)
@Rahul Read this: msdn.microsoft.com/en-us/library/…Counterpoint
S
302
i.ToString("D4");

See MSDN on format specifiers.

Sarnoff answered 1/12, 2010 at 14:22 Comment(1)
this way worked for me String.Format("{0:D4}", number);Huebner
F
127

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
Filia answered 1/9, 2011 at 8:32 Comment(1)
Just a hint: You don't need to ToString() the string. PadLeft already returns a string.Lanciform
P
72

C# 6.0 style string interpolation

int i = 1;
var str1 = $"{i:D4}";
var str2 = $"{i:0000}";
Pad answered 18/11, 2016 at 11:11 Comment(1)
This one looks very nice. Good way to avoid $"some text {x.ToStrig("D4")} after text"Polyploid
N
69

You can use:

int x = 1;
x.ToString("0000");
Narghile answered 1/12, 2010 at 14:22 Comment(1)
And a second way to use the same format string: string.Format("{0:0000}", x)Narghile
G
18
i.ToString("0000");
Greaser answered 1/12, 2010 at 14:22 Comment(0)
R
6

Easy peasy

int i = 1;
i.ToString("0###")
Renell answered 21/2, 2019 at 13:0 Comment(1)
It'd be better if you add an explanation for '#'.Around
A
5

Simply

int i=123;
string paddedI = i.ToString("D4");
Anatollo answered 2/5, 2013 at 11:57 Comment(0)
M
4

.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"  
Monophagous answered 3/7, 2019 at 18:51 Comment(1)
int i = 1002; string str = i.ToString().PadLeft(4, '0'); // returns "1002" :)Morrill
A
1
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
Artina answered 6/2, 2017 at 13:26 Comment(0)
L
1
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);
Longoria answered 19/3, 2020 at 16:32 Comment(0)
D
1

Most of the given answers are slow or very slow or don't work for negative numbers.

Try this one:

}
    //
    //
    ///<summary>Format a value with a fixed number of digits.</summary>
    public static string Pad( this long v, int digits ) {
        int negative = 0;
        if ( v < 0 ) {
            negative = 1;
            v = Math.Abs( v );
        }
        var source = v.ToString();
        var length = source.Length;
        int max = length;
        if ( max < digits ) {
            max = digits;
        }
        max += negative;
        var ca = new char[ max ];
        for ( int i = 0; i < max; i++ ) {
            ca[ i ] = '0';
        }
        while ( length > 0 ) {
            ca[ --max ] = source[ --length ];
        }
        if ( 0 != negative ) ca[ 0 ] = '-';
        return new string( ca );
    }
Duffel answered 18/11, 2021 at 8:20 Comment(0)
G
-2

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.

Guenther answered 21/6, 2017 at 6:34 Comment(0)
D
-2
string hello = "Hello C# Corner.";

string helloHash = hello.PadLeft(5, '#');  

Console.WriteLine(helloHash); 

Output :-

#####Hello C# Corner.
Description answered 6/5, 2022 at 11:22 Comment(0)
N
-5

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')
Nought answered 13/12, 2015 at 7:26 Comment(1)
Unnecessarily confusing especially when there is a very simple solution.Drench

© 2022 - 2024 — McMap. All rights reserved.