Custom numeric format string to always display the sign
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.
Beware, when using conditional formatting the negative value doesn't automatically get a sign. You need to do
string MyString = number.ToString("+#;-#;0");
You can also use format strings in string.Format(); the format string is separated from the index with a colon (':')
var f = string.Format("{0}, Force sign {0:+#;-#;+0}, No sign for zero {0:+#;-#;0}", number);
For number { +1, -1, 0 } this gives:
1, Force sign +1, No sign for zero +1
-1, Force sign -1, No sign for zero -1
0, Force sign +0, No sign for zero 0
You can also use an interpolated string instead of string.Format
to obtain the same result:
var f = $"{number}, Force sign {number:+#;-#;+0}, No sign for zero {number:+#;-#;0}";