#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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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

  1. JakeIL7 says:

    Do you cover the inverse of the Parse method, ToString() anywhere?

  2. Pingback: #1,011 – TryParse Indicates Whether a Parse Operation Will Succeed | 2,000 Things You Should Know About C#

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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: