#60 – Using Parse to Convert from String to Numeric Types

Each of the numeric types in C# has a Parse method that you can use when converting from string representations of a numeric value to an object of the appropriate numeric type.

Here are some examples:

 byte b1 = byte.Parse("200");
 sbyte sb1 = sbyte.Parse("-100");
 float f1 = float.Parse("1.2e-4");

If the string does not represent a value of the associated numeric type, or represents a numeric value that is outside the range of the type, a FormatException or OverflowException is generated.

 int n1 = int.Parse("3.4");    // FormatException
 uint ui1 = uint.Parse("-1");  // OverflowException

Numeric strings containing digit grouping (thousand separator) or decimal points are assumed to be in a format matching the current culture.  E.g. ‘.’ for decimal symbol in the US, ‘,’ for decimal symbol in France.

Advertisement