Error formatting string with number

Asked

Viewed 122 times

3

I want to format a string so it has six digits filled with zeros on the left.

I’m using the following code:

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

He’s returning the next:

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

Only three zeros are being generated and the number received.

1 answer

5


If linha.Quant be the type int remove the ToString() is not necessary:

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 number that gives the number of characters, and the second parameter if given paddingChar fills in the rest of the string of an informed nature (if not informed, 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

References:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.