C# Convert Int to String With Padding Zeros

C# convert int to string with padding zeros?

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+)

Padding integer with zeros

You can use the built-in function PadLeft:

int i = 5;
var result = i.ToString().PadLeft(8, '0');

Note: this doesn't work for negative numbers (you'd get 00000000-5).

For that you can use the built-in formatters:

int i = 5;
var result = string.Format("{0:D8}", i);

Convert int (number) to string with leading zeros? (4 digits)

Use String.PadLeft like this:

var result = input.ToString().PadLeft(length, '0');

How can I format a number into a string with leading zeros?

Rather simple:

Key = i.ToString("D2");

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

How to pad an integer number with leading zeros?

The problem is that the following:

  • .ToString()
  • .PadLeft(...)

all return a new string, they don't in any way modify the object you call the method on.

Please note that you have to place the result into a string. An integer value does not have any concept of padding, so the integer value 0010 is identical to the integer value 10.

So try this:

string value = temCode.ToString().PadLeft(4, '0');

or you can use this:

string value = temCode.ToString("d4");

or this:

string value = string.Format("{0:0000}", temCode);

Convert an integer to a binary string with leading zeros

11 is binary representation of 3. The binary representation of this value is 2 bits.

3 = 20 * 1 + 21 * 1

You can use String.PadLeft(Int, Char) method to add these zeros.

// convert number 3 to binary string. 
// And pad '0' to the left until string will be not less then 4 characters
Convert.ToString(3, 2).PadLeft(4, '0') // 0011
Convert.ToString(3, 2).PadLeft(8, '0') // 00000011

How to deal with leading zeros when formatting an int value

You can use the 0 as format specifier. From the documentation :

Replaces the zero with the corresponding digit if one is present; otherwise, zero appears in the result string.

You can do like :

02112321.ToString("00 000 000", CultureInfo.InvariantCulture)

Edit:
As indicate by @olivier-jacot-descombes, I miss a point. The OP want format a integer from a string to a string. Example "02112321" to "02 112 321".

It's possible with a intermediate conversion, string to int to string. With the example, this done "02112321" to 02112321 to "02 112 321" :

var original = "02112321";
var toInt = int.Parse(original, CultureInfo.InvariantCulture);
var formated = toInt.ToString("00 000 000", CultureInfo.InvariantCulture)

Pad with leading zeros

You can do this with a string datatype. Use the PadLeft method:

var myString = "1";
myString = myString.PadLeft(myString.Length + 5, '0');

000001




Related Topics



Leave a reply



Submit