String Format in C# – Add zeroes before number

May 8, 2011 | Posted by: admin | Asp.net, C#, Programming language | 1 Comment

In dot net we can format the numbers in easy way. We can use the static method (String.Format) or instance method (int.Tostring). Please find the below example to formate the numbers with spaces or zeroes .

Add zeroes before number
To add zeroes before a number, use colon separator “:” and write as many zeroes as you want.

String.Format(“{0:00000}”, 77);         
Result :  “00077″

String.Format(“{0:00000}”, -77);        
Result :  “-00077″

Align number to the right or left

To align number to the right, use comma „,“ followed by a number of characters. This alignment option must be before the colon separator.

String.Format(“{0,5}”, 77);
Result : “   77″

String.Format(“{0,-5}”, 77);
Result : “77   ”

String.Format(“{0,5:000}”, 77);
Result : “  077″

String.Format(“{0,-5:000}”, 77);
Result : “077  “

Different formatting for negative numbers and zero

We can have special format for negative numbers and zero. Use semicolon separator “;” to separate formatting to two or three sections. The second section is format for negative numbers, the third section is for zero.

String.Format(“{0:#;minus #}”, 77);
Result: “77″

String.Format(“{0:#;minus #}”, -77);
Result: “minus 77″

String.Format(“{0:#;minus #;zero}”, 0);
Result: “zero”

Phone number

String.Format(“{0:+### ### ### ###}”, 044123456789);
Result: “+044 123 456 789″

String.Format(“{0:##-####-####}”, 441234567);
Result: “44-123-4567″

Comments (1)

 

  1. Tyson Swee says:

    I am only commenting to make you know of the incredible discovery my cousin’s daughter enjoyed visiting your site. She even learned a good number of things, which included what it’s like to have an awesome helping mindset to make other individuals without difficulty learn about several grueling subject areas. You actually exceeded visitors’ expected results. Many thanks for distributing those essential, healthy, revealing and even fun guidance on the topic to Gloria.

Leave a Reply