String Format for Int [C#]

Integer numbers can be formatted in .NET in many ways. You can use the static method String. The format or instance method int.ToString. The following examples show how to align numbers (with spaces or zeroes), format negative numbers, or do custom formatting like phone numbers.

Add zeroes before the number.

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


String.Format("{0:00000}", 15);          // "00015"
String.Format("{0:00000}", -15);         // "-00015"

Align number to the right or left

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


String.Format("{0,5}", 15);              // "   15"
String.Format("{0,-5}", 15);             // "15   "
String.Format("{0,5:000}", 15);          // "  015"
String.Format("{0,-5:000}", 15);         // "015  "

Different formatting for negative numbers and zero

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


String.Format("{0:#;minus #}", 15);      // "15"
String.Format("{0:#;minus #}", -15);     // "minus 15"
String.Format("{0:#;minus #;zero}", 0);  // "zero"

Custom number formatting (e.g. phone number)

Numbers can be formatted also to any custom format, e.g. like phone numbers or serial numbers.


String.Format("{0:+### ### ### ###}", 447900123456); // "+447 900 123 456"
String.Format("{0:##-####-####}", 8958712551);       // "89-5871-2551"

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post