5

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.

0

4 Answers 4

21

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);
Sign up to request clarification or add additional context in comments.

3 Comments

+1, I didn't know about passing the NumberStyles. I'd still use TryParse though (I notice it takes the same parameters)...
I like this. Although what if the Currency changes?
@LB: If you're dealing with multiple currencies, I'd parse them each one at a time. Since the values themselves aren't really comparable to each other (i.e., USD$15 != CAD$15), it's somewhat meaningless to put all of them in a single array, for example.
6

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

Comments

1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.