Partager via


Parsing Numeric Strings

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

All numeric types have a static Parse method that you can use to convert the string representation of a number into a numeric value. This method allows you to parse strings that were produced using one of the format specifiers covered in Standard Numeric Format Strings and Custom Numeric Format Strings.

The characters used to represent currency symbols, thousands separators, and decimal points are defined by format providers. The Parse method accepts a format provider that allows you to parse culture-specific strings. If no format provider is specified, the provider that is associated with the current thread culture is used. For more information, see Formatting Types.

The following code example converts a string to an integer value, increments that value, and displays the result.

Dim myString As String = "12345"
Try
   Dim myInt As Integer = Integer.Parse(myString)
   myInt += 1
   outputBlock.Text &= myInt & vbCrLf
Catch e As FormatException
   outputBlock.Text &= String.Format("Unable to parse '{0}'.'", _
                                     myString) & vbCrLf
End Try
' The example displays the following output: 
'      12346
string myString = "12345";
try
{
   int myInt = int.Parse(myString);
   myInt++;
   outputBlock.Text += myInt + "\n"; 
}
catch (FormatException)
{
   outputBlock.Text += String.Format("Unable to parse '{0}'.'", 
                                     myString) + "\n";
}
// The example displays the following output: 
//      12346

Some overloads of the Parse method include a style parameter of type System.Globalization.NumberStyles. The members of the NumberStyles enumeration define the elements (such as white space, currency symbols, or thousands separators) that may be present in the string to be parsed. If these elements are not permitted by the style parameter but they are present in the string, the parse operation fails. For example, in the en-US culture, a string that contains a comma cannot be converted to an integer value using the Parse method if style does not include the NumberStyles.AllowThousands flag. Some of the styles provided by the NumberStyles enumeration include the following:

For a complete table of numeric style elements, see the NumberStyles enumeration documentation.

The following example illustrates the improper way to parse a string that contains a nonnumeric character, in this case, a thousands separator. A new CultureInfo object is first created and passed to the Int32.Parse(String, IFormatProvider) method to specify that the en-US culture should be used for parsing. Because the thousands separator is not allowed, the parse operation throws a FormatException.

Imports System.Globalization

Module Example
   Public Sub Demo(outputBlock As System.Windows.Controls.TextBlock)
      Dim myCultureInfo As New CultureInfo("en-US")
      Dim myString As String = "123,456"
      Try
         Dim myInt As Integer = Integer.Parse(myString, myCultureInfo)
         outputBlock.Text &= myInt & vbCrLf
      Catch e As FormatException
         outputBlock.Text &= String.Format("Unable to parse '{0}'.", _
                                            myString) & vbCrLf              
      End Try
   End Sub
End Module
' The example displays the following output:
'     Unable to parse '123,456'.      
using System;
using System.Globalization;

public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      CultureInfo myCultureInfo = new CultureInfo("en-US");
      string myString = "123,456";
      try
      {
         int myInt = int.Parse(myString, myCultureInfo);
         outputBlock.Text += myInt + "\n"; 
      }
      catch (FormatException)
      {
         outputBlock.Text += String.Format("Unable to parse '{0}'.", 
                                            myString) + "\n";              
      }
   }
}
// The example displays the following output:
//     Unable to parse '123,456'.      

When you apply the NumberStyles.AllowThousands flag, the Int32.Parse(String, NumberStyles, IFormatProvider) method overload handles the comma that raised the exception in the previous example. The following code example uses the same string as the previous example, but does not raise an exception. As in the previous example, a new CultureInfo object is first created. This time, it is passed to the Int32.Parse(String, NumberStyles, IFormatProvider) method overload to specify that the thousands separator used by the en-US culture is allowed in the input string.

Imports System.Globalization

Module Example
   Public Sub Demo(outputBlock As System.Windows.Controls.TextBlock)
      Dim myCultureInfo As New CultureInfo("en-US")
      Dim myString As String = "123,456"
      Try
         Dim myInt As Integer = Integer.Parse(MyString, _
                                              NumberStyles.AllowThousands, _
                                              myCultureInfo)
         outputBlock.Text &= myInt & vbCrLf
      Catch e As FormatException
         outputBlock.Text &= String.Format("Unable to parse '{0}'.", _
                                            myString)               
      End Try
   End Sub
End Module
' The example displays the following output:
'     123456      
using System;
using System.Globalization;

public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      CultureInfo myCultureInfo = new CultureInfo("en-US");
      string myString = "123,456";
      try
      {
         int myInt = int.Parse(myString, NumberStyles.AllowThousands, 
                               myCultureInfo);
         outputBlock.Text += myInt + "\n"; 
      }
      catch (FormatException)
      {
         outputBlock.Text += String.Format("Unable to parse '{0}'.", 
                                            myString) + "\n";              
      }
   }
}
// The example displays the following output:
//     123456