Amass

Forcing Sign display on Integers

January 31st, 2008 Luke

For a recent project, I needed to output integers to show the change in two values.

When an integer is negative, the negative sign(’-') is automatically added to it - but when you output an integer that is positive, there is no positive sign(’+') added to the beginning. I wanted to display the positive sign as well, so that users could easily tell when the values were positive vs. negative.

If you pass this format string into String.Format(), you will receive numbers with the proper signs applied:

"{0:+0;-0;0}"

Here are some examples:

String.Format("{0:+0;-0;0}",22); // returns "+22" String.Format("{0:+0;-0;0}",-22); // returns "-22" String.Format("{0:+0;-0;0}",0); // returns "0"

If you’re looking for a little more information on things you can do with String.Format, check out Kathy Kam’s .Net Format String 101 post.