String format in .NET: convert integer to fixed width string?

Viewed 32995

I have an int in .NET/C# that I want to convert to a specifically formatted string.

If the value is 1, I want the string to be "001".

10 = "010".

116 = "116".

etc...

I'm looking around at string formatting, but so far no success. I also won't have values over 999.

7 Answers

For the sake of completeness, this way is also possible and I prefere it because it is clearer and more flexible.

int value = 10;

// 010 
resultString = $"{value:000}";

// The result is: 010 
resultString = $"The result is: {value:000}";

If we want to use it in a function with variable fixed length output, then this approach

public string ToString(int i, int Digits)
{
 return i.ToString(string.Format("D{0}", Digits));
}

runs 20% faster than this

return i.ToString().PadLeft(Digits, '0'); 

but if we want also to use the function with a string input (e.g. HEX number) we can use this approach:

public string ToString(string value, int Digits)
 {
 int InsDigits= Digits - value.Length;
 return ((InsDigits> 0) ? new String('0', InsDigits) + value : value);
 }
Related