Click here to Skip to main content
15,889,931 members
Please Sign up or sign in to vote.
4.25/5 (3 votes)
See more:
Hi.
I wanna to add a zero at the left of a number if the number is less than 10, when the users insert it.
01
02
03
04


Could you guide me, how I can do it with String.Format.
Thanks.
Posted
Updated 16-Jan-10 6:47am
v2
Comments
Sergey Alexandrovich Kryukov 18-Dec-10 20:46pm    
What if you have more than 99 on input. Don't say "never", provide solution for all cases

You can specify a format in the ToString method of the numeric type.
i.e. an int:
int number = 2;<br />string numberString = number.ToString("00");


 
Share this answer
 
C#
static string Method1(int i)
{
    return i.ToString().PadLeft(2, '0');
}
 
Share this answer
 
v2
Or, you can do this:

string myString = string.Format("{0:00}", number);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900