使用decimal.ToString(“C”)和CultureInfo的自定义货币符号和小数位

时间:2010-02-23 07:56:18

标签: c# decimal currency

我遇到decimal.ToString("C")覆盖问题。 基本上我想做的是如下:

CultureInfo usCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = usCulture;

NumberFormatInfo LocalFormat = (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone();
LocalFormat.CurrencySymbol = "RM";

我想让上面的代码成为一个函数(覆盖ToString(“C”)),从而执行以下代码:

decimal paid = Convert.ToDecimal(dr["TotalPaids"]);
lblPaids.Text = paid.ToString("C");

结果将是RM4,900.00而不是$ 4,900.00

如何为decimal.ToString("C")创建可以解决问题的覆盖

提前致谢。

5 个答案:

答案 0 :(得分:16)

要获得RM 11,123,456.00之类的格式,您还需要设置以下属性

CurrentCulture modified = new CultureInfo(Thread.CurrentThread.CurrentCulture.Name);
Thread.CurrentThread.CurrentCulture = modified;
var numberFormat = modified.NumberFormat;
numberFormat.CurrencySymbol = "RM";
numberFormat.CurrencyDecimalDigits = 2;
numberFormat.CurrencyDecimalSeparator = ".";
numberFormat.CurrencyGroupSeparator = ",";

如果你在应用程序启动时这样做,那么应该使ms-MY格式像en-US一样,但每次调用ToString("C")方法时都会使用RM货币符号。

答案 1 :(得分:6)

如果我理解你的问题你想要的是用RM取代$。如果是这样,您需要传递自定义格式...

lblPaids.Text = paid.ToString("C", LocalFormat);

答案 2 :(得分:2)

使用此格式字符串:

#,##0.00 $;#,##0.00'-  $';0 $
decimal paid = Convert.ToDecimal(dr["TotalPaids"]);
lblPaids.Text = paid.ToString("#,##0.00 $;#,##0.00'-  $';0 $");

答案 3 :(得分:2)

您可以使用Double.ToString方法(String,IFormatProvider)https://msdn.microsoft.com/en-us/library/d8ztz0sa(v=vs.110).aspx

double amount = 1234.95;

amount.ToString("C") // whatever the executing computer thinks is the right fomat

amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-ie"))    //  €1,234.95
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("es-es"))    //  1.234,95 € 
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-GB"))    //  £1,234.95 

amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-au"))    //  $1,234.95
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-us"))    //  $1,234.95
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-ca"))    //  $1,234.95

答案 4 :(得分:-1)

lblPaids.Text = paid.ToString("C",usCulture.Name);

lblPaids.Text = paid.ToString("C",LocalFormat.Name);

必须工作