Error formatting string with number

2

I want to format a string so that it has six digits filled with leading zeros.

I'm using the following code:

string.Format("{0:000000}", linha.Quant.ToString());

It is returning the following:

67 = 00067
19 = 00019
 5 = 0005
 9 = 0009

Only three zeros are being generated and the number received.

    
asked by anonymous 14.02.2017 / 01:07

1 answer

4

If linha.Quant is of type int remove ToString() is not required:

System.Console.WriteLine(string.Format("{0:000000}", 1.ToString())); //1 - não formata
System.Console.WriteLine(string.Format("{0:000000}", 1));            //000001
System.Console.WriteLine(string.Format("{0:000000}", 10));           //000010
System.Console.WriteLine(string.Format("{0:000000}", 67));           //000067

Online Example

But a good one would be with PadLeft where:

totalWidth is the integer that informs the amount of characters, and the second parameter if it is entered paddingChar fills the rest of the string with the entered character (if not informed it is placed space ).

System.Console.WriteLine(5.ToString().PadLeft(6, '0'));  //000005
System.Console.WriteLine(67.ToString().PadLeft(6, '0')); //000067
System.Console.WriteLine(19.ToString().PadLeft(6, '0')); //000019
System.Console.WriteLine(9.ToString().PadLeft(6, '0'));  //000009

OnLine Example

14.02.2017 / 01:11