332

I have a number that I need to convert to a string. First I used this:

Key = i.ToString();

But I realize it's being sorted in a strange order and so I need to pad it with zeros. How could I do this?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mandy Weston
  • 3,435
  • 2
  • 17
  • 6
  • 9
    possible duplicate of [C# convert int to string with padding zeros?](http://stackoverflow.com/questions/4325267/c-sharp-convert-int-to-string-with-padding-zeros) – nawfal Jun 04 '15 at 07:46

11 Answers11

444

Rather simple:

Key = i.ToString("D2");

D stands for "decimal number", 2 for the number of digits to print.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mario
  • 35,726
  • 5
  • 62
  • 78
  • 8
    if you use `string.Format("D2", value)` you'll get `D2` in the output. this doesn't work. We must use `"{0:00}"` in this case. – v.oddou Aug 07 '15 at 07:22
  • 58
    You should use `string.Format("{0:D2}", value)` instead. Just saying `string.Format("D2", ...)` won't replace anything no matter what since you don't have a placeholder. – infinitypanda Sep 11 '15 at 19:25
  • 8
    @infinitypanda realize that this will only work when `value` is an int. If `value` is a double, for instance, it will have to be `string.Format("{0:00}", value)` – derekantrican Feb 23 '17 at 15:02
  • if we are talking about 'leading digits' I think the answer would be i.ToString("00"); where "00" represents the leading zeros.. you can increase this amount as much as possible. – Dedan Feb 01 '19 at 13:38
  • This will fail with `System.FormatException` if the number is a **decimal**. Better to use `.ToString("N0").PadLeft(2, '0')`. However, `PadLeft` does not work properly with negative numbers (zeros in front of negative sumbol). – Codingwiz Feb 14 '23 at 17:10
273

See String formatting in C# for some example uses of String.Format

Actually a better example of formatting int

String.Format("{0:00000}", 15);          // "00015"

or use String Interpolation:

$"{15:00000}";                           // "00015"
Paul
  • 4,009
  • 1
  • 17
  • 15
90

If you like to keep it fixed width, for example 10 digits, do it like this

Key = i.ToString("0000000000");

Replace with as many digits as you like.

i = 123 will then result in Key = "0000000123".

gog
  • 1,220
  • 11
  • 30
Øyvind Bråthen
  • 59,338
  • 27
  • 124
  • 151
78

Since nobody has yet mentioned this, if you are using C# version 6 or above (i.e. Visual Studio 2015) then you can use string interpolation to simplify your code. So instead of using string.Format(...), you can just do this:

Key = $"{i:D2}";
DavidG
  • 113,891
  • 12
  • 217
  • 223
39

use:

i.ToString("D10")

See Int32.ToString (MSDN), and Standard Numeric Format Strings (MSDN).

Or use String.PadLeft. For example,

int i = 321;
Key = i.ToString().PadLeft(10, '0');

Would result in 0000000321. Though String.PadLeft would not work for negative numbers.

See String.PadLeft (MSDN).

firefox1986
  • 1,602
  • 11
  • 9
26

For interpolated strings:

$"Int value: {someInt:D4} or {someInt:0000}. Float: {someFloat: 00.00}"
Alan Samet
  • 1,118
  • 2
  • 15
  • 18
  • This is basically the same as the [answer](https://stackoverflow.com/a/36536254/1663001) I posted 3 years before you. – DavidG Jun 29 '23 at 12:52
15

Usually String.Format("format", object) is preferable to object.ToString("format"). Therefore,

String.Format("{0:00000}", 15);  

is preferable to,

Key = i.ToString("000000");
  • 4
    Yes, as @cja asked, why is it preferable? And I'm not arguing against the assertion, I'd like to know why. – Christopher King Aug 14 '15 at 14:16
  • First syntax "feels" more precise, predictable, and clear. And it would be better stated as Key = String.Format("{0:00000}", 15); that is being compared to Key = i.ToString("000000"); With the first syntax, I'm pretty sure I know exactly the result I'll get, and if bychance I'm one character off, I know exactly what to change (format string. So, in short, to me it's preferable for emotional personal preference, weakly supported by one almost-plausible half-reason ;-) So it's decided then? – Developer63 Feb 07 '20 at 04:01
15

Try:

Key = i.ToString("000000");

Personally, though, I'd see if you can't sort on the integer directly, rather than the string representation.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
4
int num=1;
string number=num.ToString().PadLeft(4, '0')

Output="00001"

EDIT: Changed to match the PadLeft amount

maeneak
  • 573
  • 6
  • 10
3

Here I want my no to limit in 4 digit like if it is 1 it should show as 0001,if it 11 it should show as 0011..Below are the code.

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

2

I found a better way tried all the way but not worked for me

Convert.ToDecimal(LN).ToString("000000#");

LN is Int64

Monzur
  • 1,341
  • 14
  • 11