C#中如何检测字符串是否为货币

发布于 2024-12-01 17:01:39 字数 270 浏览 0 评论 0原文

通常,当我需要将货币字符串(如 1200,55 zł 或 $1,249)转换为十进制值时,我会这样做:

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

有没有办法在不检查特定货币的情况下检查字符串是否为货币?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

写下不归期 2024-12-08 17:01:39

如果您只是进行转换(您应该添加 | NumberStyles.AllowThousands
| NumberStyles.AllowDecimalPoint 也是如此),如果字符串包含当前 UI 的错误货币符号,则解析将失败 - 在这种情况下会引发异常。如果它不包含货币符号,解析仍然有效。

因此,您可以使用 TryParse 来允许这种情况并测试失败。

如果您的输入可以是任何货币,您可以使用此版本的TryParse接受 IFormatProvider 作为参数,您可以使用该参数指定有关字符串的区域性特定解析信息。因此,如果默认 UI 区域性解析失败,您可以循环尝试每个受支持的区域性。当您找到合适的货币时,您就会获得您的号码和货币类型(兹罗提、美元、欧元、卢布等)。

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

海螺姑娘 2024-12-08 17:01:39

据我了解,最好这样做:

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

参见 Jeff Atwood 有关 TryParse 的描述。它不会抛出异常,并且在异常情况下比 Parse 快得多。

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.

浅忆流年 2024-12-08 17:01:39

要检查字符串是否是用于输入工资的货币金额 - 我使用了以下内容:

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

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

豆芽 2024-12-08 17:01:39

您可以尝试在字符串中搜索您认为是货币符号的内容,然后在字典中查找它是否确实是货币符号。我只会查看字符串的开头和结尾,并挑选出任何不是数字的内容,然后这就是您要查找的内容。 (如果两端都有东西,那么我认为您可以假设它不是货币。)

这种方法的优点是您只需扫描字符串一次,并且不必单独测试每种货币。

这是我的想法的一个例子,尽管它可能需要一些改进:

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

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));
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文