开发者

Custom Currency symbol and decimal places using decimal.ToString("C") and CultureInfo

开发者 https://www.devze.com 2022-12-21 11:29 出处:网络
I have a problem with decimal.ToString(\"C\") override. Basically what I wants to do is as follows: CultureInfo usCulture = new CultureInfo(\"en-US\");

I have a problem with decimal.ToString("C") override. Basically what I wants to do is as follows:

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

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

I wants to make above code a function (override ToString("C")) whereby when the following code get executed:

decimal paid = Convert.ToDecimal(dr["TotalPaids"]);
lblPaids.Text = paid.ToS开发者_JAVA百科tring("C");

The results would be RM4,900.00 instead of $4,900.00

How do I create an override for decimal.ToString("C") that would solve my problem

Thanks in advance.


To get a format like RM 11,123,456.00 you also need to set the following properties

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 = ",";

If you do that at application startup then that should make ms-MY format like en-US but with the RM currency symbol every time you call the ToString("C") method.


If I understand your question correctly what you want is to replace the $ with RM. If so, you need to pass the custom format...

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


use this format string :

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


You can use the Double.ToString Method (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


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

Or

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

must Work

0

精彩评论

暂无评论...
验证码 换一张
取 消