Format integer value in format "000"

5

In vb6 I used the following line of code that allowed to format the value "1" to "001"

Format$(Nivel, "000")

In C # I'm using the following with similar nomenclature.

string.Format("000", 1);

However, the return value is always "000"

    
asked by anonymous 13.03.2018 / 15:05

3 answers

4

To work, 2 examples (one with PadLeft and the other one with string.Format ):

int i = 1;
Console.WriteLine($"{i}".PadLeft(3,'0'));
Console.WriteLine(string.Format("{0:000}", i));

Example ONLINE Ideone

13.03.2018 / 15:15
6

It's possible this way too.

int a  =  3;
string valor = a.ToString("D3");
    
13.03.2018 / 15:20
3

The right way to do what you want is to use PadLeft() :

string valor = "1";
valor.PadLeft(3, '0');
    
13.03.2018 / 15:10