How to detect if string is currency in c#

旧巷老猫 提交于 2019-12-05 00:11:40

问题


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?


回答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.)




回答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.




回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/7214513/how-to-detect-if-string-is-currency-in-c-sharp

标签

工具导航Map

JSON相关