4

I would like to format an integer 9 to "09" and 25 to "25".

How can this be done?

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
AntonioC
  • 437
  • 2
  • 5
  • 16

4 Answers4

18

You can use either of these options:

The "0" Custom Specifier

  • value.ToString("00")
  • String.Format("{0:00}", value)

The Decimal ("D") Standard Format Specifier

  • value.ToString("D2")
  • String.Format("{0:D2}", value)

For more information:

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
1

If its just leading zero's that you want, you can use this:

value.tostring.padleft("0",2)
value.ToString().PadLeft(2, '0');   // C#

If you have 2 digits, say 25 for example, you will get "25" back....if you have just one digit, say 9 for example, you will get "09"....It is worth noting that this gives you a string back, and not an integer, so you may need to cast this later on in your code.

msmith
  • 9
  • 4
Gavin Perkins
  • 685
  • 1
  • 9
  • 28
0

String formate is the best way to do that. It's will only add leading zero for a single length. 9 to "09" and 25 to "25".

String.format("%02d", value)

Bonus: If you want to add multiple leading zero 9 to "0009" and 1000 to "1000". That's means you want a string for 4 indexes so the condition will be %04d.

String.format("%04d", value)
Md Imran Choudhury
  • 9,343
  • 4
  • 62
  • 60
-8

I don't know the exact syntax. But in any language, it would look like this.

a = 9
aString =""

if a < 10 then 
  aString="0" + a 
else 
  aString = "" + a
end if
durbnpoisn
  • 4,666
  • 2
  • 16
  • 30
  • @user19127 : This is _**definiately not failsafe!**_ One should never use the `+` operator when concatenating strings with numbers. Use the `&` operator for proper AND failsafe concatenation. **See: http://stackoverflow.com/a/734631/3740093** – Visual Vincent Dec 28 '15 at 22:20