Recipe 1.8. Determining Whether a String Is a Valid NumberProblemYou have a string that possibly contains a numeric value. You need to know whether this string contains a valid number. SolutionUse the static TryParse method of any of the numeric types. For example, to determine whether a string contains a double, use the following method: string str = "12.5"; double result = 0; if(double.TryParse(str, System.Globalization.NumberStyles.Float, System.Globalization.NumberFormatInfo.CurrentInfo, out result)) { // Is a double! } DiscussionThis recipe shows how to determine whether a string contains only a numeric value. The tryParse method returns true if the string contains a valid number without the exception that you will get if you use the Parse method. Since TRyParse does not throw exceptions, it performs better over time given a set of strings where some do not contain numbers. See AlsoSee the "Parse" and "TryParse" topics in the MSDN documentation. |