Custom numeric format string to always display the sign

Viewed 111118

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!)

6 Answers

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");

For a numeric expression of any type:

+###,###,###,###,###,###,###,###,###,##0.###,###,###,###,###,###,###,###,###,###;-###,###,###,###,###,###,###,###,###,##0.###,###,###,###,###,###,###,###,###,###;0

Use three parts for three cases: positive;negative;zero

Other aspects of the example:

  • Zero is not signed. You could have it show as anything, such as "zero".

  • Absolute values less than one have a leading 0 before the decimal point. Adjust to taste.

  • Number of digits is for the largest and smallest absolute decimal values. Adjust to taste.

  • Decimal point character is culture-specific. .NET substitutes.

  • Grouping separators are optional. The character is culture-specific. .NET substitutes. (The positions are also culture-specific but that's only controlled by your format string.) You also use any other character except the special characters for Format (which include , . # 0).

I cannot comment so i Do an answer here (nuts reputation system ....)

You can Use number.ToString("+0;-#") very well to Produce the UTC String TimeFormat

Here showed in PowerShell code

"$([System.DateTime]::Now.ToString('HH:mm:ss.fff'))$($([System.TimeZoneInfo]::Local.GetUtcOffset([System.DateTime]::Now).TotalMinutes.ToString('+0;-#')))"

Thank you @gcores https://stackoverflow.com/users/40256/gcores

Related