According to http://msdn.microsoft.com/en-us/library/6t7dwaa5.aspx, if I want to display a number as a currency, I can call .ToString() and pass a parameter, in this case "C"
However, based upon the details below which is from the MSDN site, it automatically removes the minus (-) character, meaning my value is now positive.
int value = -16325;
// Display value using default ToString method.
Console.WriteLine(value.ToString()); // Displays -16325
// Display value using some standard format specifiers.
Console.WriteLine(value.ToString("G")); // Displays -16325
Console.WriteLine(value.ToString("C")); // Displays ($16,325.00)
Console.WriteLine(value.ToString("D")); // Displays -16325
Console.WriteLine(value.ToString("F")); // Displays -16325.00
Console.WriteLine(value.ToString("N")); // Displays -16,325.00
Console.WriteLine(value.ToString("X")); // Displays FFFFC03B
So, how do I keep it with the minus symbol, would I have to use the Contains("-") method and if it's true add the - back on.
Something like this code (apologies if it's coded incorrectly, but you get the idea).
string x = (value.ToString().Contains("-") : "-" + value.ToString("C") ? + value.ToString("C"));
This depends on the value of your CurrentCulture.NumberFormat.CurrencyNegativePattern
. Possible values are from 0 - 15:
0 : ($12,345.00)
1 : -$12,345.00
2 : $-12,345.00
3 : $12,345.00-
4 : (12,345.00$)
5 : -12,345.00$
6 : 12,345.00-$
7 : 12,345.00$-
8 : -12,345.00 $
9 : -$ 12,345.00
10 : 12,345.00 $-
11 : $ 12,345.00-
12 : $ -12,345.00
13 : 12,345.00- $
14 : ($ 12,345.00)
15 : (12,345.00 $)
So it looks like you want to set it to 1
to get the output you are after with something like:
int value = -12345;
var numberFormat = (NumberFormatInfo)CultureInfo.CurrentCulture.NumberFormat.Clone();
numberFormat.CurrencyNegativePattern = 1;
string numberAsCurrency = value.ToString("C", numberFormat)
Though, based on your comments about it being a remote server and you always want to format in a specific way it may be better to just set the culture for the whole thread to a controlled value and this will affect all subsequent ToString()
calls on that thread:
int value = -12345;
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyNegativePattern = 1;
string numberAsCurrency = value.ToString("C");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With