
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Determining Whether a String Is a Valid Number
|
11
The other static methods of the Convert class, such as ToByte, ToInt64, and ToInt16,
also have this same overload, which accepts a number as a string and the base in
which this number is expressed. Unfortunately, these methods convert from a string
value expressed in base2, base8, base10, and base16 only. They do not allow for con-
verting a value to a string expressed in any other base types than base10. However,
the
ToString methods on the various numeric types do allow for this conversion.
See Also
See the “Convert Class” and “Converting with System.Convert” topics in the MSDN
documentation.
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 deter-
mine 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