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 (eg 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 eg
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.
public static class MyExtensions
{
public static string GetMoney(this decimal value, bool displayCurrency = false, bool displayPeriods = true)
{
string ret = string.Format("{0:C}", value).Substring(displayCurrency ? 0 : 1);
if (!displayPeriods)
{
ret = ret.Replace(",", string.Empty);
}
return ret;
}
}
To use this extension method:
decimal test = 40023.2345M;
string myValue = test.GetMoney(displayCurrency:true, displayPeriods:false);`
Converting the integer value into $0.00 format
int Value = 1000; string abc = Convert.ToDecimal(Value).ToString("$0.00"); output will be $1000.00
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.