4

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

How can this be done?

Alexander Abakumov
  • 12,301
  • 14
  • 79
  • 125
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
  • 112,050
  • 16
  • 178
  • 345
1

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

value.tostring.padleft("0",2)

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.

Gavin Perkins
  • 633
  • 1
  • 9
  • 23
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
  • 8,089
  • 4
  • 53
  • 55
-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,628
  • 2
  • 15
  • 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