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"

Alignment

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:
{0:[positive];[negative];[zero]}

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

Hexadecimal

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

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

Happy formatting. 🙂
Dave

1 comment… add one

Leave a Comment