Ok, I admit that I'm probably the last .NET developer on earth to learn about this, but just in case I'm not I thought I'd better blog about it.

A program I have here at work needed to be able to read text from the clipboard. The text should be a list of dollar-values, and because it was most-likely copied from Excel its formatting could easily contain dollar signs and commas, and even leading or traliing spaces (eg "$2,517.32  "). So I needed to be able to parse a string like that into a Double value.

Up until today I've been cheating, using code like this:

    string s = "$2,517.32 ";
    s = s.Replace("$", "").Replace(",", "").Trim();
    double d = double.Parse(s); 

Pretty awkward, but it has done the trick.

Anyway, today I found out about the System.Globalization.NumberStyles enumeration. This is a great little enum that you can pass as a parameter to "Parse" which gives it some hints about what to expect in the incoming string. By combining values like NumberStyles.AllowCurrencySymbol and NumberStyles.AllowThousands, you can have the Parse method ignore specific symbols. Better still, they're culture-specific, so if you're in the UK and use the pound-sign as your currency symbol, it'll take that into account.

NumberStyles even has some predefined values like NumberStyles.Float and NumberStyles.Integer, which combine several settings into one.

So my newly-revised code looks something like this:

    string s = "$2,517.32 ";
    double d = double.Parse(s, System.Globalization.NumberStyles.Currency); 

Et voila! Pretty neat, huh?