Best way to convert decimal or string to currency in C#?

心已入冬 提交于 2019-11-30 18:15:49

问题


I've been trying to find best way to convert decimal/string to currency depending on my choice.

        public static string returnWaluta(string varS, string varSymbol) {
        decimal varD = decimal.Parse(varS);
        if (varSymbol == "EUR") {
            Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR", false);
            return String.Format("{0:c}", varD);
        } else if (varSymbol == "PLN") {
            Thread.CurrentThread.CurrentCulture = new CultureInfo("pl-PL", false);
            return String.Format("{0:c}", varD);
        } else if (varSymbol == "USD") {
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US", false);
            return String.Format("{0:c}", varD);
        } else {
            // Not handled currency
            MessageBox.Show(varSymbol);
            return varS.ToString();
        }
    }
   public static string returnWaluta(decimal varS, string varSymbol) {
        if (varSymbol == "EUR") {
            Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR", false);
            return String.Format("{0:c}", varS);
        } else if (varSymbol == "PLN") {
            Thread.CurrentThread.CurrentCulture = new CultureInfo("pl-PL", false);
            return String.Format("{0:c}", varS);
        } else if (varSymbol == "USD") {
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US", false);
            return String.Format("{0:c}", varS);
        } else {
            // Not handled currency
            MessageBox.Show(varSymbol);
            return varS.ToString();
        }
   }

Is this good aproach or i could do this better? I get data from SQL database. I get decimal value and currency it is on (like EUR, USD, PLN). This seems to work but maybe there's better option? Also for now this is single threaded aplication, am i making global change when i change Thread.CurrentThread.CurrentCulture or is it just temporary until i return from the method?

With regards,

MadBoy


回答1:


You can pass the culture you want in as the first parameters to string.Format. That would be better than making the change to the current thread every time. You may want to set up some sort of map or dictionary that makes the mapping from a currency code to a culture code for you as well - this would greatly reduce the number of lines of code here.

return string.Format(new CultureInfo(map[currencyCode], false), "{0:c}", varD);

Or if you store a map of CultureInfo instances against a currency code, you'd have this:

return string.Format(cultureMap[currencyCode], "{0:c}", varD);



回答2:


Convert.ToDecimal()


来源:https://stackoverflow.com/questions/2093423/best-way-to-convert-decimal-or-string-to-currency-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!