C# convertir int a cadena con ceros de relleno?


En C# tengo un valor entero que necesita ser convertido a cadena pero necesita agregar ceros antes:

Por Ejemplo:

int i = 1;

Cuando lo convierto en cadena, debe convertirse en 0001

Necesito saber la sintaxis en C#.

Author: Pinu, 2010-12-01

10 answers

i.ToString().PadLeft(4, '0') - vale, pero no funciona para números negativos
i.ToString("0000"); - forma explícita
i.ToString("D4"); - especificador de formato de formulario corto

 561
Author: Jay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-28 10:11:17
i.ToString("D4");

Ver MSDN en los especificadores de formato.

 253
Author: Ryan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-01 14:22:21

Este es un buen ejemplo:

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
 105
Author: Denys Wessels,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-25 17:26:46

Puedes usar:

int x = 1;
x.ToString("0000");
 63
Author: Yodan Tauber,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-01 14:22:07

Interpolación de cadena de estilo C# 6.0

int i = 1;
var str1 = $"{i:D4}";
var str2 = $"{i:0000}";
 27
Author: Dr Blowhard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-18 11:11:27
i.ToString("0000");
 17
Author: Justin Niessner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-01 14:22:15

Simplemente

int i=123;
string paddedI = i.ToString("D4");
 1
Author: cahit beyaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-08 17:26:15
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
 0
Author: Serge,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-06 13:26:39

Aquí quiero rellenar mi número con 4 dígitos. Por ejemplo, si es 1 entonces debería mostrarse como 0001, si es 11 debería mostrarse como 0011.

A continuación se muestra el código que logra esto:

reciptno=1; // Pass only integer.

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

TxtRecNo.Text = formatted; // Output=0001

Implementé este código para generar el número de recibo de dinero para un archivo PDF.

 0
Author: saktiprasad swain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-30 15:13:50

Para rellenar int i para que coincida con la longitud de la cadena de int x, cuando ambos pueden ser negativos:

i.ToString().PadLeft((int)Math.Log10(Math.Abs(x < 0 ? x * 10 : x)) + 1, '0')
 -4
Author: xnp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-13 07:54:04