335

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?

1

11 Answers 11

450

Rather simple:

Key = i.ToString("D2");

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

5
  • 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 7, 2015 at 7: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. Sep 11, 2015 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) Feb 23, 2017 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 1, 2019 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 at 17:10
276

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"
3
  • 8
    Note that String.Format("{0:00000}", "15"); returns "15", i.e. it does not work on a string. May 10, 2019 at 11:42
  • 7
    Even shorter way: $"{15:D5}"; will result in an output of: "00015".
    – Al Dass
    Sep 23, 2020 at 20:50
  • 3
    If you have int i and want 8 digits, simply use var iStr = $"{i:D8}.
    – Matt
    Feb 9, 2022 at 10:35
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".

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}";
0
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).

2
  • 5
    I'd guess that will screw you once you try to use it with negative numbers.
    – Mario
    Mar 24, 2011 at 11:32
  • Thanks - I used the second one. I left out the ".ToString()" - it still works. Mar 25, 2019 at 4:07
26

For interpolated strings:

$"Int value: {someInt:D4} or {someInt:0000}. Float: {someFloat: 00.00}"
4
  • This is basically the same as the answer I posted 3 years before you.
    – DavidG
    Jun 29 at 12:52
  • @DavidG I suspect there was some sort of housekeeping with questions and responses getting merged. Paul posted basically the same answer five years before you.
    – Alan Samet
    Oct 6 at 5:20
  • Paul edited their question in 2019 to include the updated info. I added my answer in 2016.
    – DavidG
    Oct 6 at 7:29
  • @DavidG I feel like it's kindof nuts that I've got someone on StackOverflow on the other side of the world accusing me of some committing sort of stolen valor over posting a bit of syntax that's built into a language.
    – Alan Samet
    Oct 10 at 21:54
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.

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");
2
  • 5
    Yes, as @cja asked, why is it preferable? And I'm not arguing against the assertion, I'd like to know why. Aug 14, 2015 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? Feb 7, 2020 at 4:01
4
int num=1;
string number=num.ToString().PadLeft(4, '0')

Output="00001"

EDIT: Changed to match the PadLeft amount

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.