I have an integer variable .if its 1-9 it only displays as "1" or "9", I'm looking to convert the variable to save as 3 digits, ie. "001", or "009", etc. any ideas? I am using C#,ASP.Net
Asked
Active
Viewed 2.8k times
6 Answers
30
use
int X = 9;
string PaddedResult = X.ToString().PadLeft (3, '0'); // results in 009

Yahia
- 69,653
- 9
- 115
- 144
-
I prefer the readability of the format string but if you're doing it lots, I suspect this will be faster right? – LexyStardust May 31 '12 at 11:49
-
@LexyStardust it might be faster but I like it because the length of the string can be a variable (first parameter in the call to Pad...) which in turn makes it rather easy to configure... – Yahia May 31 '12 at 11:51
-
Sorry I meant that this solution would be faster - won't be all the funky lookups to FormatProviders that goes underneath Format(). – LexyStardust May 31 '12 at 11:55
20
What about
var result = String.Format("{0:000}", X);
var result2 = X.ToString("000");

Jürgen Steinblock
- 30,746
- 24
- 119
- 189
3
The "D" (or decimal) format specifier converts a number to a string of decimal digits (0-9), prefixed by a minus sign if the number is negative.
The precision specifier indicates the minimum number of digits desired in the resulting string. If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier.
Like:
int value;
value = 12345;
Console.WriteLine(value.ToString("D"));
// Displays 12345
Console.WriteLine(value.ToString("D8"));
// Displays 00012345
value = -12345;
Console.WriteLine(value.ToString("D"));
// Displays -12345
Console.WriteLine(value.ToString("D8"));
// Displays -00012345

MCollard
- 926
- 2
- 20
- 39
0
you can use this code also
int k = 5;
string name = $"name-{k++:D3}.ext";

hossein sedighian
- 1,711
- 1
- 13
- 16