开发者

Converting string to decimal

开发者 https://www.devze.com 2022-12-09 21:00 出处:网络
In C#, I\'m trying to convert a string to decimal. For example, the string is \"(USD 92.90)\" How would you parse th开发者_C百科is out as a decimal with Decimal.Parse fcn.I\'m going on the assumptio

In C#, I'm trying to convert a string to decimal.

For example, the string is "(USD 92.90)"

How would you parse th开发者_C百科is out as a decimal with Decimal.Parse fcn.


I'm going on the assumption here that the string you're trying to parse is an actual currency value.

CultureInfo c = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name);
c.NumberFormat.CurrencyNegativePattern = 14; // From MSDN -- no enum values for this
c.NumberFormat.CurrencySymbol = "USD";

decimal d = Decimal.Parse("(USD 92.90)", NumberStyles.Currency, c);


You could start off with a reg-exp to extract the number part and then use Decimal.TryParse to parse the sub-string.


First, get the number out of the string. A Regex \d+(.\d+)? might help there. Although you could use substring, if the characters around that number are always the same.

Then use Decimal.Parse (or Double.Parse) on that string.


When parsing strings, I always prefer to use TryParse to avoid exceptions being thrown for invalid strings:

        string str =  "(USD 92.90)";
        decimal result;
        if (Decimal.TryParse(str, out result))
        {
            // the parse worked
        }
        else
        {
            // Invalid string
        }

And as others have said, first use a regular expression to extract just the numerical part.

0

精彩评论

暂无评论...
验证码 换一张
取 消