Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format Negative numbers in parenthesis BUT NOT with $ symbol?

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)
like image 953
user715993 Avatar asked Sep 05 '25 03:09

user715993


2 Answers

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)
like image 51
Edmund Schweppe Avatar answered Sep 09 '25 15:09

Edmund Schweppe


You can use the FormatNumber function:

FormatNumber(-100, UseParensForNegativeNumbers:=TriState.True)

will return "(100)"

There's more on MSDN

like image 21
Jon Egerton Avatar answered Sep 09 '25 16:09

Jon Egerton