18

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

MartW
  • 12,348
  • 3
  • 44
  • 68
user1270940
  • 221
  • 1
  • 5
  • 9

6 Answers6

30

use

int X = 9;

string PaddedResult = X.ToString().PadLeft (3, '0'); // results in 009

see MSDN references here and here.

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
6
int i = 5;
string tVal=i.ToString("000");
Mohan Gopi
  • 237
  • 1
  • 4
  • 12
3

From: https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings#DFormatString

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
int i = 5;
string retVal = i.ToString().PadLeft(3, '0');
Kishore Kumar
  • 12,675
  • 27
  • 97
  • 154
0

you can use this code also

int k = 5;
string name =  $"name-{k++:D3}.ext";
hossein sedighian
  • 1,711
  • 1
  • 13
  • 16