given value = 2 or 4.00
the below statement outputs
value = Convert.ToDecimal(value).ToString("C2");
value = $2.00, or $4.00
if I have value = 1000 then output will be $1,000.00 but I require $1000.00.
I don't prefer string concatenation of "$" and value.
var stringValue = Convert.ToDecimal(value).ToString("$0.00");
As noted by @James below, this hard-codes the currency into the format. Using the format C2 will use the system currency format. This can be changed for the system (e.g. in Windows 7 - Start - Control Panel - Change Display Language - Additional Settings - Currency - Digit grouping) and will allow the C2 format to display the currency value without the comma when running on that particular system.
EDIT
All credit to @James for using the current culture. My only modification to his answer would be to clone the current NumberFormat so as to get all the properties of the current culture number format before removing the CurrencyGroupSeparator.
var formatInfo = (NumberFormatInfo)CultureInfo.CurrentCulture.NumberFormat.Clone();
formatInfo.CurrencyGroupSeparator = string.Empty;
var stringValue = Convert.ToDecimal(value).ToString("C", formatInfo);
You should use the NumberFormat class to specify the type of formatting you need, ToString takes an IFormatProvider parameter e.g.
var formatInfo = (System.Globalization.NumberFormatInfo)CultureInfo.CurrentCulture.NumberFormat.Clone();
formatInfo.CurrencyGroupSeparator = ""; // remove the group separator
Console.WriteLine(2.ToString("C", formatInfo));
Console.WriteLine(4.ToString("C", formatInfo));
Console.WriteLine(1000.ToString("C", formatInfo));
This will keep your number formatting consistent with whichever culture you are using.
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