Compartir a través de


Double.Parse Method (String, NumberStyles, IFormatProvider)

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

Converts the string representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent.

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

Syntax

'Declaration
Public Shared Function Parse ( _
    s As String, _
    style As NumberStyles, _
    provider As IFormatProvider _
) As Double
public static double Parse(
    string s,
    NumberStyles style,
    IFormatProvider provider
)

Parameters

  • s
    Type: System.String
    A string that contains a number to convert.
  • provider
    Type: System.IFormatProvider
    An object that supplies culture-specific formatting information about s.

Return Value

Type: System.Double
A double-precision floating-point number that is equivalent to the numeric value or symbol specified in s.

Exceptions

Exception Condition
ArgumentNullException

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

FormatException

s does not represent a numeric value.

ArgumentException

style is not a NumberStyles value.

-or-

style is the NumberStyles.AllowHexSpecifier value.

OverflowException

s represents a number that is less than MinValue or greater than MaxValue.

Remarks

The style parameter defines the style elements (such as white space, thousands separators, and currency symbols) that are allowed in the s parameter for the parse operation to succeed. It must be a combination of bit flags from the NumberStyles enumeration. The following NumberStyles members are not supported:

The s parameter can contain NumberFormatInfo.PositiveInfinitySymbol, NumberFormatInfo.NegativeInfinitySymbol, or NumberFormatInfo.NaNSymbol for the culture specified by provider. Depending on the value of style, it can also take the form:

[ws] [$] [sign][integral-digits,]integral-digits[.[fractional-digits]][E[sign]exponential-digits][ws]

Elements framed in square brackets ([ and ]) are optional. The following table describes each element.

Element

Description

ws

A series of white-space characters. White space can appear at the beginning 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

A negative sign symbol (-) or a positive sign symbol (+). The sign can appear at the beginning 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.

integral-digits

A series of digits ranging from 0 to 9 that specify the integral part of the number. The integral-digits element can be absent if the string contains the fractional-digits element.

,

A culture-specific group separator. The current culture's group separator symbol 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.

fractional-digits

A series of digits ranging from 0 to 9 that specify the fractional part of the number. Fractional digits can appear in s if style includes the NumberStyles.AllowDecimalPoint flag.

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.

exponential-digits

A series of digits ranging from 0 to 9 that specify an exponent.

A string with digits only (which corresponds to the NumberStyles.None style) always parses successfully. The remaining System.Globalization.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 flags affect the elements that may be present in s.

NumberStyles value

Elements permitted in s in addition to digits

None

The integral-digits element only.

AllowDecimalPoint

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

AllowExponent

The "e" or "E" character, which indicates exponential notation. This flag by itself supports values in the form digitsEdigits; additional flags are needed to successfully parse strings with such elements as positive or negative signs and decimal point symbols.

AllowLeadingWhite

The ws element at the beginning of s.

AllowTrailingWhite

The ws element at the end of s.

AllowLeadingSign

The sign element at the beginning 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 thousands 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 beginning or end of s, sign at the beginning of s, and the decimal point (.) symbol. The s parameter can also use exponential notation.

Number

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

Any

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

The provider parameter is an IFormatProvider implementation whose GetFormat method returns a NumberFormatInfo object that supplies culture-specific information used in interpreting the format of s. Typically, it is a NumberFormatInfo or CultureInfo object. If provider is nulla null reference (Nothing in Visual Basic) or a NumberFormatInfo cannot be obtained, the formatting information for the current system culture is used.

Ordinarily, if you pass the Double.Parse method a string that is created by calling the Double.ToString method, the original Double value is returned. However, because of a loss of precision, the values may not be equal. In addition, attempting to parse the string representation of either MinValue or MaxValue throws an OverflowException, as the following example illustrates.

Dim value As String

value = Double.MinValue.ToString()
Try
   outputBlock.Text += Double.Parse(value).ToString() + vbCrLf
Catch e As OverflowException
   outputBlock.Text += String.Format("{0} is outside the range of the Double type.", _
                                     value) + vbCrLf
End Try

value = Double.MaxValue.ToString()
Try
   outputBlock.Text += Double.Parse(value).ToString() + vbCrLf
Catch e As OverflowException
   outputBlock.Text += String.Format("{0} is outside the range of the Double type.", _
                                     value) + vbCrLf
End Try
' The example displays the following output:
'    -1.79769313486232E+308 is outside the range of the Double type.
'    1.79769313486232E+308 is outside the range of the Double type.            
   string value;

   value = Double.MinValue.ToString();
   try {
      outputBlock.Text += Double.Parse(value) + "\n";
   }   
   catch (OverflowException) {
      outputBlock.Text += String.Format("{0} is outside the range of the Double type.\n",
                        value);
   }

   value = Double.MaxValue.ToString();
   try {
      outputBlock.Text += Double.Parse(value) + "\n";
   }
   catch (OverflowException) {
      outputBlock.Text += String.Format("{0} is outside the range of the Double type.\n",
                        value);
   }
// The example displays the following output:
//    -1.79769313486232E+308 is outside the range of the Double type.
//    1.79769313486232E+308 is outside the range of the Double type.

If a separator is encountered in the s parameter during a parse operation, and the applicable currency or number decimal and group separators are the same, the parse operation assumes that the separator is a decimal separator rather than a group separator. For more information about separators, see CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparator, and NumberGroupSeparator.

Examples

The following example illustrates the use of the Parse(String, NumberStyles, IFormatProvider) method to assign several string representations of temperature values to a Temperature object.

Imports System.Globalization

Public Class Temperature
   ' Parses the temperature from a string. Temperature scale is 
   ' indicated by 'F (for Fahrenheit) or 'C (for Celcius) at the end
   ' of the string.
   Public Shared Function Parse(ByVal s As String, ByVal styles As NumberStyles, _
                                ByVal provider As IFormatProvider) As Temperature
      Dim temp As New Temperature()

      If s.TrimEnd(Nothing).EndsWith("'F") Then
         temp.Value = Double.Parse(s.Remove(s.LastIndexOf("'"c), 2), _
                                   styles, provider)
      Else
         If s.TrimEnd(Nothing).EndsWith("'C") Then
            temp.Celsius = Double.Parse(s.Remove(s.LastIndexOf("'"c), 2), _
                                        styles, provider)
         Else
            temp.Value = Double.Parse(s, styles, provider)
         End If
      End If
      Return temp
   End Function

   ' Declare private constructor so Temperature so only Parse method can
   ' create a new instance
   Private Sub New()
   End Sub

   Protected m_value As Double

   Public Property Value() As Double
      Get
         Return m_value
      End Get

      Private Set(ByVal value As Double)
         m_value = value
      End Set
   End Property

   Public Property Celsius() As Double
      Get
         Return (m_value - 32) / 1.8
      End Get
      Private Set(ByVal value As Double)
         m_value = value * 1.8 + 32
      End Set
   End Property

   Public ReadOnly Property Fahrenheit() As Double
      Get
         Return m_value
      End Get
   End Property
End Class

Public Module Example
   Public Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)
      Dim value As String
      Dim styles As NumberStyles
      Dim provider As IFormatProvider
      Dim temp As Temperature

      value = "25,3'C"
      styles = NumberStyles.Float
      provider = New CultureInfo("fr-FR")
      temp = Temperature.Parse(value, styles, provider)
      outputBlock.Text += String.Format("{0} degrees Fahrenheit equals {1} degrees Celsius.", _
                        temp.Fahrenheit, temp.Celsius) + vbCrLf

      value = " (40) 'C"
      styles = NumberStyles.AllowLeadingWhite Or NumberStyles.AllowTrailingWhite _
               Or NumberStyles.AllowParentheses
      provider = NumberFormatInfo.InvariantInfo
      temp = Temperature.Parse(value, styles, provider)
      outputBlock.Text += String.Format("{0} degrees Fahrenheit equals {1} degrees Celsius.", _
                        temp.Fahrenheit, temp.Celsius) + vbCrLf

      value = "5,778E03'C"      ' Approximate surface temperature of the Sun
      styles = NumberStyles.AllowDecimalPoint Or NumberStyles.AllowThousands Or _
               NumberStyles.AllowExponent
      provider = New CultureInfo("en-GB")
      temp = Temperature.Parse(value, styles, provider)
      outputBlock.Text += String.Format("{0} degrees Fahrenheit equals {1} degrees Celsius.", _
                        temp.Fahrenheit.ToString("N"), temp.Celsius.ToString("N")) + vbCrLf

   End Sub
End Module
using System;
using System.Globalization;

public class Temperature
{
   // Parses the temperature from a string. Temperature scale is 
   // indicated by 'F (for Fahrenheit) or 'C (for Celcius) at the end
   // of the string.
   public static Temperature Parse(string s, NumberStyles styles,
                                   IFormatProvider provider)
   {
      Temperature temp = new Temperature();

      if (s.TrimEnd(null).EndsWith("'F"))
      {
         temp.Value = Double.Parse(s.Remove(s.LastIndexOf((char)39), 2),
                                   styles, provider);
      }
      else
      {
         if (s.TrimEnd(null).EndsWith("'C"))
            temp.Celsius = Double.Parse(s.Remove(s.LastIndexOf((char)39), 2),
                                        styles, provider);
         else
            temp.Value = Double.Parse(s, styles, provider);
      }
      return temp;
   }

   // Declare private constructor so Temperature so only Parse method can
   // create a new instance
   private Temperature() { }

   protected double m_value;

   public double Value
   {
      get { return m_value; }
      private set { m_value = value; }
   }

   public double Celsius
   {
      get { return (m_value - 32) / 1.8; }
      private set { m_value = value * 1.8 + 32; }
   }

   public double Fahrenheit
   {
      get { return m_value; }
   }
}

public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      string value;
      NumberStyles styles;
      IFormatProvider provider;
      Temperature temp;

      value = "25,3'C";
      styles = NumberStyles.Float;
      provider = new CultureInfo("fr-FR");
      temp = Temperature.Parse(value, styles, provider);
      outputBlock.Text += String.Format("{0} degrees Fahrenheit equals {1} degrees Celsius.",
                        temp.Fahrenheit, temp.Celsius) + "\n";

      value = " (40) 'C";
      styles = NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite
               | NumberStyles.AllowParentheses;
      provider = NumberFormatInfo.InvariantInfo;
      temp = Temperature.Parse(value, styles, provider);
      outputBlock.Text += String.Format("{0} degrees Fahrenheit equals {1} degrees Celsius.",
                        temp.Fahrenheit, temp.Celsius) + "\n";

      value = "5,778E03'C";      // Approximate surface temperature of the Sun
      styles = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands |
               NumberStyles.AllowExponent;
      provider = new CultureInfo("en-GB");
      temp = Temperature.Parse(value, styles, provider);
      outputBlock.Text += String.Format("{0} degrees Fahrenheit equals {1} degrees Celsius.",
                        temp.Fahrenheit.ToString("N"), temp.Celsius.ToString("N")) + "\n";
   }
}

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.