Recipe1.8.Determining Whether a String Is a Valid Number


Recipe 1.8. Determining Whether a String Is a Valid Number

Problem

You have a string that possibly contains a numeric value. You need to know whether this string contains a valid number.

Solution

Use 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!     } 

Discussion

This 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 Also

See the "Parse" and "TryParse" topics in the MSDN documentation.



C# Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2004
Pages: 424

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net