37

How do I use the ToString method on an integer to display a 2-char

int i = 1; i.ToString() -> "01" instead of "1"

Thanks.

Ray
  • 12,101
  • 27
  • 95
  • 137

6 Answers6

82

You can use i.ToString("D2") or i.ToString("00")

See Standard Numeric Format Strings and Custom Numeric Format Strings on Microsoft Docs for more details

Patrick McDonald
  • 64,141
  • 14
  • 108
  • 120
16

This should do it:

String.Format("{0:00}",i);

Here's a link to an msdn article on using custom formatting strings: http://msdn.microsoft.com/en-us/library/0c899ak8.aspx

Chris Trombley
  • 2,232
  • 1
  • 17
  • 24
7

In order to ensure at least 2 digits are displayed use the "00" format string.

i.ToString("00");

Here is a handy reference guide for all of the different ways numeric strings can be formatted

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
5

In C# 6 you could write:

var i = 1;
var stringI = $"{i:D2}";

$ - string interpolation

pfx
  • 20,323
  • 43
  • 37
  • 57
Steve Homayooni
  • 135
  • 5
  • 11
3

i.ToString("00") Take a look at this for more rules.

rerun
  • 25,014
  • 6
  • 48
  • 78
0

In any case you wanna check first if it's only 1 number, use Regular Expression:

Regex OneNumber = new Regex("^[0-9]$");
OneNumber.Replace(i.ToString(), "0" + i)
Mayer Spitz
  • 2,577
  • 1
  • 20
  • 26