问题
I have seen all over the internet to format a NEGATIVE double value with a parenthesis WITH a $
symbol ie. currency type.
I am looking for a .NET format string, to format
12345.67 = 12,345.67
-12345.67 = (12,345.67)
回答1:
MSDN on conditional formatting to the rescue!
You can specify up to three different sections of your format string at once, separating them with semicolons. If you specify two format string sections, the first is used for positive and zero values while the second is used for negative values; if you use three sections, the first is used for positive values, the second for negative values, and the third for zero values.
The output from this C# code:
string fmt1 = "#,##0.00";
string fmt2 = "#,##0.00;(#,##0.00)";
double posAmount = 12345.67;
double negAmount = -12345.67;
Console.WriteLine("posAmount.ToString(fmt1) returns " + posAmount.ToString(fmt1));
Console.WriteLine("negAmount.ToString(fmt1) returns " + negAmount.ToString(fmt1));
Console.WriteLine("posAmount.ToString(fmt2) returns " + posAmount.ToString(fmt2));
Console.WriteLine("negAmount.ToString(fmt2) returns " + negAmount.ToString(fmt2));
is:
posAmount.ToString(fmt1) returns 12,345.67
negAmount.ToString(fmt1) returns -12,345.67
posAmount.ToString(fmt2) returns 12,345.67
negAmount.ToString(fmt2) returns (12,345.67)
回答2:
You can use the FormatNumber function:
FormatNumber(-100, UseParensForNegativeNumbers:=TriState.True)
will return "(100)"
There's more on MSDN
来源:https://stackoverflow.com/questions/8344575/format-negative-numbers-in-parenthesis-but-not-with-symbol