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
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);
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