Format Negative numbers in parenthesis BUT NOT with $ symbol?

ぐ巨炮叔叔 提交于 2019-12-17 23:44:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!