LB.
LB.

Reputation: 14112

Converting string to decimal

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

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

How would you parse this out as a decimal with Decimal.Parse fcn.

Upvotes: 5

Views: 1534

Answers (4)

Skizz
Skizz

Reputation: 71070

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

Upvotes: 6

Jon Seigel
Jon Seigel

Reputation: 12401

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

Upvotes: 21

Philip Wallace
Philip Wallace

Reputation: 8015

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.

Upvotes: 0

Hans Kesting
Hans Kesting

Reputation: 39284

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.

Upvotes: 1

Related Questions