Formatting Integers in C#

String Operations

In this post I am going to show you a few different ways how you can format an integer (int).

Padding with Zeroes

To pad your integer with zeroes write your format string with a colon (‘:’) and include as many zeroes as you wish after the colon ({0:[your zeroes]}). Below are a few examples.

string.Format("{0:00000}", 123);        // "00123"
string.Format("{0:00000}", -123);       // "-00123"

string.Format("{0:00000}", 5);          // "00005"
string.Format("{0:00000}", -5);         // "-00005"

string.Format("{0:00000}", 12345);      // "12345"
string.Format("{0:00000}", -12345);     // "-12345"

string.Format("{0:00000}", 12345678);   // "12345678"
string.Format("{0:00000}", -12345678);  // "-12345678"

Custom Formats

You can create your own custom formats as shown below. The ‘#’ character represents a number placeholder.

string.Format("{0:###-###-###-###}", 125658986325);  // "125-658-986-325"
string.Format("{0:+### ## ### ###}", 35621123456);   // "+356 21 123 456"


To specify alignment to the Format method you must write your format string as shown below. Note we are using a comma (‘,’) to specify the number of characters used for alignment.

{0,[no. of chars]} and if you want to pad with zeroes {0,[no. of chars]:0000}

string.Format("{0,6}", 27);       // "    27"
string.Format("{0,-6}", 27);      // "27    "
string.Format("{0,6:0000}", 27);  // "  0027"
string.Format("{0,-6:0000}", 27); // "0027  "

Positive and Negative Numbers, and Zero

You can include different formats for positive numbers, negative numbers, and zero by using the semicolon character (‘;’).

Format string:

string.Format("{0:#;(#);zero}", 23);  // "23"
string.Format("{0:#;(#);zero}", -23); // "(23)"
string.Format("{0:#;(#);zero}", 0);   // "zero"


You can also format your integer as a hexadecimal like this:

string.Format("{0:X}", 12345678);  // "BC614E"

Happy formatting. 🙂
Dave runs on the Thesis Theme

How smart is your Theme? How good is your support? Check out ThesisTheme for WordPress.

The Thesis Theme is one of the best Wordpress frameworks out there, especially if you understand software development, which since you're here you probably do. Thesis allows you to design post and page templates using a drag-and-drop system which gives you access to all the relevant page elements you would normally have to manually access through code. This is why understanding development techniques definitely helps, even though you don't need to write any code to get Thesis up and running.

So go check out the incredible features at DIYThemes and start using Thesis now!

1 comment… add one
  • zx10r

    Great information. Thanks

Leave a Comment