Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does String.Format converts minus to parenthesis

I am using String.Format to add $ sign into values.

 var result = string.Format("{0:C}", Convert.ToDecimal(amount));

when amount is negative it converts minus sign into parenthesis- like below

-11.00 --> ($11.00)

I need this

-11.00 --> -$11.00

How can I fix this ?

like image 717
R15 Avatar asked Dec 04 '25 06:12

R15


2 Answers

Parentheses is the preferred accounting format to display negative currency, in the US at least. See this UX.SE post.

If you don't want to follow that convention, you can create your own NumberFormatInfo:

var format = CultureInfo.CreateSpecificCulture("en-US").NumberFormat;

// "1" means "-$n"
format.CurrencyNegativePattern = 1;

string.Format(format, "{0:C}", -1m) // "-$1.00"

See this for a list of the values that you can put in CurrencyNegativePattern.

like image 109
Sweeper Avatar answered Dec 06 '25 22:12

Sweeper


You actually have a lot of control over how your numbers are output, if you don't want to use the standard cultures. In fact you can make up you're own currency symbols if you want.

Here's how you can customize the decimal.ToString output:

var money = -4.21345m;

var ni = new System.Globalization.NumberFormatInfo()
{
    CurrencySymbol = "₿",
    CurrencyDecimalDigits = 5,
};

for (var i = 0; i < 16; i++)
{
    ni.CurrencyNegativePattern = i;
    Console.WriteLine(money.ToString("C", ni));
}

That gives me:

(₿4.21345)
-₿4.21345
₿-4.21345
₿4.21345-
(4.21345₿)
-4.21345₿
4.21345-₿
4.21345₿-
-4.21345 ₿
-₿ 4.21345
4.21345 ₿-
₿ 4.21345-
₿ -4.21345
4.21345- ₿
(₿ 4.21345)
(4.21345 ₿)
like image 39
Enigmativity Avatar answered Dec 06 '25 22:12

Enigmativity