tags:

views:

73

answers:

2

What is the best way to convert any currency into decimal in C#?

public static decimal returnDecimalFromCurrency(string dataToCheck) {

  decimal varValue;
  if (!Decimal.TryParse(dataToCheck, NumberStyles.Number | NumberStyles.AllowCurrencySymbol, CultureInfo.CurrentCulture, out varValue)) {
    varValue = decimal.MinValue;
  }
  return varValue;
}

But this one does work for only my current currency. If i pass it EURO currency it won't get converted.

Or the only way is to always check what currency it is and pass proper CultureInfo:

CultureInfo.GetCultureInfo("pl-PL") for zl, or CultureInfo.GetCultureInfo("en-GB") for pounds?

Edit:

Or maybe this is the quick "working" hack?

 Decimal.TryParse(dataToCheck.Trim().Replace("zł", "").Replace("€", ""), NumberStyles.Number | NumberStyles.AllowCurrencySymbol, CultureInfo.GetCultureInfo("pl-PL"), out varValue)

But to be honest I don't really like it.

+1  A: 

I'd avoid trying to parse the currency with Decimal.TryParse and instead strip off the currency - giving the resultant string to TryParse. Deal with the currency separately - of course, create a function to do this if you need to do it more than once.

Will A
I had it done like that before but that just doesn't seem right `Decimal.TryParse(dataToCheck.Trim().Replace("zł", "").Replace("€", ""), NumberStyles.Number | NumberStyles.AllowCurrencySymbol, CultureInfo.GetCultureInfo("pl-PL"), out varValue)`
MadBoy
I think much better would be to use a regular expression to strip off the currency - I would imagine it's safe to assume that a currency will not include a digit - so something like the following is what you need.` Console.WriteLine(Regex.Match("£123.45", "^[^0-9.]*(.*)").Groups[1].Value);`
Will A
in different language there's sometimes , instead of .
MadBoy
+1  A: 

Here 's what works for me, I hope it helps you too:

    public static decimal Parse(string currencyString)
    {
        return Parse(currencyString, Thread.CurrentThread.CurrentCulture);
    }

    public static decimal Parse(string currencyString, CultureInfo culture)
    {
        currencyString = currencyString.Replace(culture.NumberFormat.CurrencySymbol, System.String.Empty);
        var value = Convert.ToDecimal(currencyString, culture);
        return value;
    }
Ioannis Karadimas
This doesn't really work for me. Generates an error.
MadBoy