How to: Determine Whether a String Represents a Numeric Value

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

To determine whether a string is a valid representation of a specified numeric type, use the static TryParse method that is implemented by all primitive numeric types and also by types such as DateTime and IPAddress. The following example shows how to determine whether “108” is a valid int.

int i = 0;   
string s = "108";  
bool result = int.TryParse(s, out i); //i now = 108  

If the string contains nonnumeric characters or the numeric value is too large or too small for the particular type you have specified, TryParse returns false and sets the out parameter to zero. Otherwise, it returns true and sets the out parameter to the numeric value of the string.

System_CAPS_ICON_note.jpg Note
A string may contain only numeric characters and still not be valid for the type whose TryParse method that you use. For example, “256” is not a valid value for byte but it is valid for int. “98.6” is not a valid value for int but it is a valid decimal.

The following examples show how to use TryParse with string representations of longbyte, and decimal values.

              string numString = "1287543"; //"1287543.0" will return false for a long
              long number1 = 0;
              bool canConvert = long.TryParse(numString, out number1);
              if (canConvert == true)
                Console.WriteLine("number1 now = {0}", number1);
                Console.WriteLine("numString is not a valid long");

              byte number2 = 0;
              numString = "255"; // A value of 256 will return false
              canConvert = byte.TryParse(numString, out number2);
              if (canConvert == true)
                Console.WriteLine("number2 now = {0}", number2);
                Console.WriteLine("numString is not a valid byte");

              decimal number3 = 0;
              numString = "27.3"; //"27" is also a valid decimal
              canConvert = decimal.TryParse(numString, out number3);
              if (canConvert == true)
                Console.WriteLine("number3 now = {0}", number3);
                Console.WriteLine("number3 is not a valid decimal");

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: