Question

I added a variable of type int and I used it to call something like:

x.ToString("0000");

I changed x to type string and now the above is invalid. Is the only way to format x now:

string.Format("{0:0000}",x);

or is there a short-cut?

I am using StringBuilder to build the string, so does the same apply for AppendFormat?

Was it helpful?

Solution

No real shortcut.

Int32 doesn't have a concept of how many leading zeros the int should have.

You're doing the correct thing by formatting to string. If you're using that to display stuff, it shouldn't really be an issue ( you still have x if you want to perform numeric operations ).

AppendFormat works like string.Format, but appends to the StringBuilder object it is called on.

OTHER TIPS

You can't format the string as you do a numeric value, so if you want to apply numeric formatting to the string you have to parse it to a number first:

Int32.Parse(x).ToString("0000")

Unfortunately, this is the best way. Remember that each type has its own ToString method that can be overridden. The int type's ToString allows you to pass a format to format the integer when converted to string. The DateTime is also similar. However, a string type's ToString only returns the string because the source is already a string type. To format a string, you must call string.Format.

No.

You have to convert the string representation of an integer to an actual integer so that it can be correctly formatted with the required number of leading zeros.

If the string is already in that format why do you need to reformat it?

MSDN shows some ways using a specifier: http://msdn.microsoft.com/en-us/library/fzeeb5cd.aspx#Y759

Example

x.ToString("G");

This link lists all the format options: http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

x.PadLeft(4, '0'); 

would provide the same result as

x.ToString("0000"); 

provided that x is still a number (it's a string so there's no way to be sure of that without at least TryCast()-ing it back.

Use string interpolation (starting with C# 6).

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated

{<interpolationExpression>[,<alignment>][:<formatString>]}

With your example:

$"{x:0000}"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top