How to detect if string is currency in c#

10,449

Solution 1

If you just do the conversion (you should add | NumberStyles.AllowThousands | NumberStyles.AllowDecimalPoint as well) then if the string contains the wrong currency symbol for the current UI the parse will fail - in this case by raising an exception. It it contains no currency symbol the parse will still work.

You can therefore use TryParse to allow for this and test for failure.

If your input can be any currency you can use this version of TryParse that takes a IFormatProvider as argument with which you can specify the culture-specific parsing information about the string. So if the parse fails for the default UI culture you can loop round each of your supported cultures trying again. When you find the one that works you've got both your number and the type of currency it is (Zloty, US Dollar, Euro, Rouble etc.)

Solution 2

As I understand it's better to do:

decimal value = -1;
if (Decimal.TryParse(dataToCheck.Trim(), NumberStyles.Number | 
  NumberStyles.AllowCurrencySymbol,currentCulture, out value)
   {do something}

See Jeff Atwood description about TryParse. It doesn't throw an exception and extremely faster than Parse in exception cases.

Solution 3

To check if a string is a currency amount that would be used for entering wages - I used this:

    public bool TestIfWages(string wages)
            {
                Regex regex = new Regex(@"^\d*\.?\d?\d?$");
                bool y = regex.IsMatch(wages);
                return y;
            }

Solution 4

You might try searching the string for what you think is a currency symbol, then looking it up in a dictionary to see if it really is a currency symbol. I would just look at the beginning of the string and the end of the string and pick out anything that's not a digit, then that's what you look up. (If there's stuff at both ends then I think you can assume it's not a currency.)

The advantage to this approach is that you only have to scan the string once, and you don't have to test separately for each currency.

Here's an example of what I had in mind, although it could probably use some refinement:

class Program
{
    private static ISet<string> _currencySymbols = new HashSet<string>() { "$", "zł", "€", "£" };

    private static bool StringIsCurrency(string str)
    {
        // Scan the beginning of the string until you get to the first digit
        for (int i = 0; i < str.Length; i++)
        {
            if (char.IsDigit(str[i]))
            {
                if (i == 0)
                {
                    break;
                }
                else
                {
                    return StringIsCurrencySymbol(str.Substring(0, i).TrimEnd());
                }
            }
        }
        // Scan the end of the string until you get to the last digit
        for (int i = 0, pos = str.Length - 1; i < str.Length; i++, pos--)
        {
            if (char.IsDigit(str[pos]))
            {
                if (i == 0)
                {
                    break;
                }
                else
                {
                    return StringIsCurrencySymbol(str.Substring(pos + 1, str.Length - pos - 1).TrimStart());
                }
            }
        }
        // No currency symbol found
        return false;
    }

    private static bool StringIsCurrencySymbol(string symbol)
    {
        return _currencySymbols.Contains(symbol);
    }

    static void Main(string[] args)
    {
        Test("$1000.00");
        Test("500 zł");
        Test("987");
        Test("book");
        Test("20 €");
        Test("99£");
    }

    private static void Test(string testString)
    {
        Console.WriteLine(testString + ": " + StringIsCurrency(testString));
    }
}
Share:
10,449
MadBoy
Author by

MadBoy

CEO of Evotec. I have a blog that has lots of technical articles and nice PowerShell based modules. I also have polish version of my website although blog content/technical stuff is in English. If you fancy PowerShell you can have a look at my GitHub projects. Whether you just want to use those or help you're very welcome! If you want to contact me visit my website and all the information you need is there.

Updated on June 04, 2022

Comments

  • MadBoy
    MadBoy almost 2 years

    Usually when I have need to convert currency string (like 1200,55 zł or $1,249) to decimal value I do it like this:

    if (currencyString.Contains("zł)) {
        decimal value = Decimal.Parse(dataToCheck.Trim(), NumberStyles.Number | NumberStyles.AllowCurrencySymbol);
    }
    

    Is there a way to check if string is currency without checking for specific currency?