C# Int16 Parse(String, NumberStyles)
Description
Int16 Parse(String, NumberStyles)
converts the string
representation of a number in a specified style to its 16-bit signed integer
equivalent.
Syntax
Int16.Parse(String, NumberStyles)
has the following syntax.
public static short Parse(
string s,
NumberStyles style
)
Parameters
Int16.Parse(String, NumberStyles)
has the following parameters.
s
- A string containing a number to convert.style
- A bitwise combination of the enumeration values that indicates the style elements that can be present in s. A typical value to specify is NumberStyles.Integer.
Returns
Int16.Parse(String, NumberStyles)
method returns A 16-bit signed integer equivalent to the number specified in s.
Example
The following example uses the Int16.Parse(String, NumberStyles) method to parse the string representations of Int16 values using the en-US culture.
//w w w.j a v a 2 s . c o m
using System;
using System.Globalization;
public class ParseSample
{
public static void Main()
{
string value;
NumberStyles style;
// Parse a number with a thousands separator (throws an exception).
value = "12,345";
style = NumberStyles.None;
ParseToInt16(value, style);
style = NumberStyles.AllowThousands;
ParseToInt16(value, style);
// Parse a number with a thousands separator and decimal point.
value = "12,345.00";
style = NumberStyles.AllowThousands | NumberStyles.Integer |
NumberStyles.AllowDecimalPoint;
ParseToInt16(value, style);
// Parse a number with a fractional component (throws an exception).
value = "12,345.001";
ParseToInt16(value, style);
// Parse a number in exponential notation.
value = "123E02";
style = style | NumberStyles.AllowExponent;
ParseToInt16(value, style);
// Parse a number in exponential notation with a positive sign.
value = "123E+02";
ParseToInt16(value, style);
// Parse a number in exponential notation with a negative sign
// (throws an exception).
value = "145E-02";
ParseToInt16(value, style);
}
private static void ParseToInt16(string value, NumberStyles style)
{
try
{
short number = Int16.Parse(value, style);
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
catch (FormatException)
{
Console.WriteLine("Unable to parse '{0}' with style {1}.", value,
style.ToString());
}
catch (OverflowException)
{
Console.WriteLine("'{0}' is out of range of the Int16 type.", value);
}
}
}
The code above generates the following result.