Custom numeric format string to always display the sign


Question

Is there any way I can specify a standard or custom numeric format string to always output the sign, be it +ve or -ve (although what it should do for zero, I'm not sure!)

1
171
3/12/2014 8:04:24 AM

Accepted Answer

Yes, you can. There is conditional formatting. See Conditional formatting in MSDN

eg:

string MyString = number.ToString("+0;-#");

Where each section separated by a semicolon represents positive and negative numbers

or:

string MyString = number.ToString("+#;-#;0");

if you don't want the zero to have a plus sign.

274
5/24/2016 9:50:23 PM

Beware, when using conditional formatting the negative value doesn't automatically get a sign. You need to do

string MyString = number.ToString("+#;-#;0");

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon