如何检测,如果字符串是货币在C# [英] How to detect if string is currency in c#

查看:97
本文介绍了如何检测,如果字符串是货币在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,当我有需要货币字符串(如1200,55兹罗提或$ 1,249)转换为十进制值我这样做是这样的:

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?

推荐答案

如果你只是做转换(您应该添加 | NumberStyles.AllowThousands $ b $ C | - 通过引发异常在这种情况下,它不包含货币符号NumberStyles.AllowDecimalPoint 为好),然后如果字符串包含当前的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.

您可以因此使用的TryParse 考虑到这一点,并测试失败。

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

如果您的输入可以是任何一种货币可以使用这个版本的的TryParse ,需要一个的IFormatProvider 与您可以指定有关特定文化的解析信息参数串。因此,如果解析为默认的UI文化可以循环轮每个支持的区域性的尝试再次失败。当你发现你的作品已经得到了双方你的电话号码和货币类型之一是(兹罗提,美元,欧元,卢布等)

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

这篇关于如何检测,如果字符串是货币在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆