Поделиться через


UInt16.Parse Method (String, NumberStyles)

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Updated: August 2009

Converts the string representation of a number in a specified style to its 16-bit unsigned integer equivalent.

This API is not CLS-compliant. The CLS-compliant alternative is Parse(String).

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

Syntax

'Declaration
<CLSCompliantAttribute(False)> _
Public Shared Function Parse ( _
    s As String, _
    style As NumberStyles _
) As UShort
[CLSCompliantAttribute(false)]
public static ushort Parse(
    string s,
    NumberStyles style
)

Parameters

  • s
    Type: System.String
    A string that represents the number to convert. The string is interpreted by using the style specified by the style parameter.

Return Value

Type: System.UInt16
A 16-bit unsigned integer equivalent to the number specified in s.

Exceptions

Exception Condition
ArgumentNullException

s is nulla null reference (Nothing in Visual Basic).

ArgumentException

style is not a NumberStyles value.

-or-

style is not a combination of NumberStyles.AllowHexSpecifier and NumberStyles.HexNumber values.

FormatException

s is not in a format compliant with style.

OverflowException

s represents a number less than UInt16.MinValue or greater than UInt16.MaxValue.

-or-

s includes non-zero, fractional digits.

Remarks

The style parameter defines the style elements (such as white space, the positive or negative sign symbol, the group separator symbol, or the decimal point symbol) that are allowed in the s parameter for the parse operation to succeed. style must be a combination of bit flags from the NumberStyles enumeration. The style parameter makes this method overload useful when s contains the string representation of a hexadecimal value, when the number system (decimal or hexadecimal) represented by s is known only at run time, or when you want to disallow white space or a sign symbol in s.

Depending on the value of style, the s parameter may include the following elements:

[ws][$][sign][digits,]digits[.fractional_digits][E[sign]exponential_digits][ws]

Elements in square brackets ([ and ]) are optional. If style includes NumberStyles.AllowHexSpecifier, the s parameter may contain the following elements:

[ws]hexdigits[ws]

The following table describes each element.

Element

Description

ws

Optional white space. White space can appear at the start of s if style includes the NumberStyles.AllowLeadingWhite flag, and it can appear at the end of s if style includes the NumberStyles.AllowTrailingWhite flag.

$

A culture-specific currency symbol. Its position in the string is defined by the NumberFormatInfo.CurrencyNegativePattern and NumberFormatInfo.CurrencyPositivePattern properties of the current culture. The current culture's currency symbol can appear in s if style includes the NumberStyles.AllowCurrencySymbol flag.

sign

An optional sign. The sign can appear at the start of s if style includes the NumberStyles.AllowLeadingSign flag, and it can appear at the end of s if style includes the NumberStyles.AllowTrailingSign flag. Parentheses can be used in s to indicate a negative value if style includes the NumberStyles.AllowParentheses flag. However, the negative sign symbol can be used only with zero; otherwise, the method throws an OverflowException.

digits

fractional_digits

exponential_digits

A sequence of digits from 0 through 9. For fractional_digits, only the digit 0 is valid.

,

A culture-specific group separator symbol. The current culture's group separator can appear in s if style includes the NumberStyles.AllowThousands flag.

.

A culture-specific decimal point symbol. The current culture's decimal point symbol can appear in s if style includes the NumberStyles.AllowDecimalPoint flag. Only the digit 0 can appear as a fractional digit for the parse operation to succeed; if fractional_digits includes any other digit, a FormatException is thrown.

E

The "e" or "E" character, which indicates that the value is represented in exponential (scientific) notation. The s parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag.

hexdigits

A sequence of hexadecimal digits from 0 through f, or 0 through F.

A string with digits only (which corresponds to the NumberStyles.None style) always parses successfully. Most of the remaining NumberStyles members control elements that may be present, but are not required to be present, in the input string. The following table indicates how individual NumberStyles members affect the elements that may be present in s.

NumberStyles value

Elements permitted in s in addition to digits

None

The digits element only.

AllowDecimalPoint

The decimal point (.) and fractional-digits elements.

AllowExponent

The "e" or "E" character, which indicates exponential notation, along with exponential_digits.

AllowLeadingWhite

The ws element at the start of s.

AllowTrailingWhite

The ws element at the end of s.

AllowLeadingSign

The sign element at the start of s.

AllowTrailingSign

The sign element at the end of s.

AllowParentheses

The sign element in the form of parentheses enclosing the numeric value.

AllowThousands

The group separator (,) element.

AllowCurrencySymbol

The currency ($) element.

Currency

All elements. However, s cannot represent a hexadecimal number or a number in exponential notation.

Float

The ws element at the start or end of s, sign at the start of s, and the decimal point (.) symbol. The s parameter can also use exponential notation.

Number

The ws, sign, group separator (,), and decimal point (.) elements.

Any

All elements. However, s cannot represent a hexadecimal number.

Unlike the other NumberStyles values, which allow for, but do not require, the presence of particular style elements in s, the NumberStyles.AllowHexSpecifier style value means that the individual numeric characters in s are always interpreted as hexadecimal characters. Valid hexadecimal characters are 0-9, A-F, and a-f. The only other flags that can be combined with the style parameter are NumberStyles.AllowLeadingWhite and NumberStyles.AllowTrailingWhite. (The NumberStyles enumeration includes a composite number style, NumberStyles.HexNumber, that includes both white-space flags.)

NoteNote:

If s is the string representation of a hexadecimal number, it cannot be preceded by any decoration (such as 0x or &h) that differentiates it as a hexadecimal number. This causes the conversion to fail.

The s parameter is parsed by using the formatting information in a NumberFormatInfo object that is initialized for the current system culture. To specify the culture whose formatting information is used for the parse operation, call the Parse(String, NumberStyles, IFormatProvider) overload.

Examples

The following example tries to parse each element in a string array by using a number of NumberStyles values.

Imports System.Globalization

Module Example
   Public Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)
      Dim values() As String = {" 214 ", "1,064", "(0)", "1241+", " + 214 ", " +214 ", "2153.0", "1e03", "1300.0e-2"}
      Dim whitespace As NumberStyles = NumberStyles.AllowLeadingWhite Or NumberStyles.AllowTrailingWhite
      Dim styles() As NumberStyles = {NumberStyles.None, _
                                       whitespace, _
                                       NumberStyles.AllowLeadingSign Or NumberStyles.AllowTrailingSign Or whitespace, _
                                       NumberStyles.AllowThousands Or NumberStyles.AllowCurrencySymbol, _
                                       NumberStyles.AllowExponent Or NumberStyles.AllowDecimalPoint}

      ' Attempt to convert each number using each style combination.
      For Each value As String In values
         outputBlock.Text += String.Format("Attempting to convert '{0}':", value) & vbCrLf
         For Each style As NumberStyles In styles
            Try
               Dim number As UShort = UInt16.Parse(value, style)
               outputBlock.Text += String.Format("   {0}: {1}", style, number) & vbCrLf
            Catch e As FormatException
               outputBlock.Text += String.Format("   {0}: Bad Format", style) & vbCrLf
            End Try
         Next
         outputBlock.Text &= vbCrLf
      Next
   End Sub
End Module
' The example displays the following output:
'    Attempting to convert ' 214 ':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: 214
'       Integer, AllowTrailingSign: 214
'       AllowThousands, AllowCurrencySymbol: Bad Format
'       AllowDecimalPoint, AllowExponent: Bad Format
'    
'    Attempting to convert '1,064':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: Bad Format
'       Integer, AllowTrailingSign: Bad Format
'       AllowThousands, AllowCurrencySymbol: 1064
'       AllowDecimalPoint, AllowExponent: Bad Format
'    
'    Attempting to convert '(0)':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: Bad Format
'       Integer, AllowTrailingSign: Bad Format
'       AllowThousands, AllowCurrencySymbol: Bad Format
'       AllowDecimalPoint, AllowExponent: Bad Format
'    
'    Attempting to convert '1241+':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: Bad Format
'       Integer, AllowTrailingSign: 1241
'       AllowThousands, AllowCurrencySymbol: Bad Format
'       AllowDecimalPoint, AllowExponent: Bad Format
'    
'    Attempting to convert ' + 214 ':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: Bad Format
'       Integer, AllowTrailingSign: Bad Format
'       AllowThousands, AllowCurrencySymbol: Bad Format
'       AllowDecimalPoint, AllowExponent: Bad Format
'    
'    Attempting to convert ' +214 ':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: Bad Format
'       Integer, AllowTrailingSign: 214
'       AllowThousands, AllowCurrencySymbol: Bad Format
'       AllowDecimalPoint, AllowExponent: Bad Format
'    
'    Attempting to convert '2153.0':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: Bad Format
'       Integer, AllowTrailingSign: Bad Format
'       AllowThousands, AllowCurrencySymbol: Bad Format
'       AllowDecimalPoint, AllowExponent: 2153
'    
'    Attempting to convert '1e03':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: Bad Format
'       Integer, AllowTrailingSign: Bad Format
'       AllowThousands, AllowCurrencySymbol: Bad Format
'       AllowDecimalPoint, AllowExponent: 1000
'    
'    Attempting to convert '1300.0e-2':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: Bad Format
'       Integer, AllowTrailingSign: Bad Format
'       AllowThousands, AllowCurrencySymbol: Bad Format
'       AllowDecimalPoint, AllowExponent: 13
Imports System.Globalization

Module Example
   Public Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)
      ' Define a custom culture that uses "++" as a positive sign. 
      Dim ci As CultureInfo = New CultureInfo("")
      ci.NumberFormat.PositiveSign = "++"
      ' Create an array of cultures.
      Dim cultures() As CultureInfo = {ci, CultureInfo.InvariantCulture}
      ' Create an array of strings to parse.
      Dim values() As String = {"++1403", "-0", "+0", "+16034", _
                                 Int16.MinValue.ToString(), "14.0", "18012"}
      ' Parse the strings using each culture.
      For Each culture As CultureInfo In cultures
         outputBlock.Text += String.Format("Parsing with the '{0}' culture.", culture.Name) & vbCrLf
         For Each value As String In values
            Try
               Dim number As UShort = UInt16.Parse(value, culture)
               outputBlock.Text += String.Format("   Converted '{0}' to {1}.", value, number) & vbCrLf
            Catch e As FormatException
               outputBlock.Text += String.Format("   The format of '{0}' is invalid.", value) & vbCrLf
            Catch e As OverflowException
               outputBlock.Text += String.Format("   '{0}' is outside the range of a UInt16 value.", value) & vbCrLf
            End Try
         Next
      Next
   End Sub
End Module
' The example displays the following output:
'       Parsing with the  culture.
'          Converted '++1403' to 1403.
'          Converted '-0' to 0.
'          The format of '+0' is invalid.
'          The format of '+16034' is invalid.
'          '-32768' is outside the range of a UInt16 value.
'          The format of '14.0' is invalid.
'          Converted '18012' to 18012.
'       Parsing with the '' culture.
'          The format of '++1403' is invalid.
'          Converted '-0' to 0.
'          Converted '+0' to 0.
'          Converted '+16034' to 16034.
'          '-32768' is outside the range of a UInt16 value.
'          The format of '14.0' is invalid.
'          Converted '18012' to 18012.
using System;
using System.Globalization;

public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      string[] values = { " 214 ", "1,064", "(0)", "1241+", " + 214 ", " +214 ", "2153.0", "1e03", "1300.0e-2" };
      NumberStyles whitespace = NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite;
      NumberStyles[] styles = { NumberStyles.None, whitespace, 
                                NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign | whitespace, 
                                NumberStyles.AllowThousands | NumberStyles.AllowCurrencySymbol, 
                                NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint };

      // Attempt to convert each number using each style combination.
      foreach (string value in values)
      {
         outputBlock.Text += String.Format("Attempting to convert '{0}':", value) + "\n";
         foreach (NumberStyles style in styles)
         {
            try
            {
               ushort number = UInt16.Parse(value, style);
               outputBlock.Text += String.Format("   {0}: {1}", style, number) + "\n";
            }
            catch (FormatException)
            {
               outputBlock.Text += String.Format("   {0}: Bad Format", style) + "\n";
            }
         }
         outputBlock.Text += "\n";
      }
   }
}
// The example display the following output:
//    Attempting to convert ' 214 ':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: 214
//       Integer, AllowTrailingSign: 214
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert '1,064':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: 1064
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert '(0)':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert '1241+':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: 1241
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert ' + 214 ':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert ' +214 ':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: 214
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert '2153.0':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: 2153
//    
//    Attempting to convert '1e03':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: 1000
//    
//    Attempting to convert '1300.0e-2':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: 13
using System;
using System.Globalization;

public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      // Define a custom culture that uses "++" as a positive sign. 
      CultureInfo ci = new CultureInfo("");
      ci.NumberFormat.PositiveSign = "++";
      // Create an array of cultures.
      CultureInfo[] cultures = { ci, CultureInfo.InvariantCulture };
      // Create an array of strings to parse.
      string[] values = { "++1403", "-0", "+0", "+16034", 
                          Int16.MinValue.ToString(), "14.0", "18012" };
      // Parse the strings using each culture.
      foreach (CultureInfo culture in cultures)
      {
         outputBlock.Text += String.Format("Parsing with the '{0}' culture.", culture.Name) + "\n";
         foreach (string value in values)
         {
            try
            {
               ushort number = UInt16.Parse(value, culture);
               outputBlock.Text += String.Format("   Converted '{0}' to {1}.", value, number) + "\n";
            }
            catch (FormatException)
            {
               outputBlock.Text += String.Format("   The format of '{0}' is invalid.", value) + "\n";
            }
            catch (OverflowException)
            {
               outputBlock.Text += String.Format("   '{0}' is outside the range of a UInt16 value.", value) + "\n";
            }
         }
      }
   }
}
// The example displays the following output:
//       Parsing with the  culture.
//          Converted '++1403' to 1403.
//          Converted '-0' to 0.
//          The format of '+0' is invalid.
//          The format of '+16034' is invalid.
//          '-32768' is outside the range of a UInt16 value.
//          The format of '14.0' is invalid.
//          Converted '18012' to 18012.
//       Parsing with the '' culture.
//          The format of '++1403' is invalid.
//          Converted '-0' to 0.
//          Converted '+0' to 0.
//          Converted '+16034' to 16034.
//          '-32768' is outside the range of a UInt16 value.
//          The format of '14.0' is invalid.
//          Converted '18012' to 18012.

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Change History

Date

History

Reason

August 2009

Revised extensively.

Information enhancement.