Aracılığıyla paylaş


Double.TryParse Method (String, NumberStyles, IFormatProvider, Double%)

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. A return value indicates whether the conversion succeeded or failed.

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

Syntax

'Declaration
Public Shared Function TryParse ( _
    s As String, _
    style As NumberStyles, _
    provider As IFormatProvider, _
    <OutAttribute> ByRef result As Double _
) As Boolean
public static bool TryParse(
    string s,
    NumberStyles style,
    IFormatProvider provider,
    out double result
)

Parameters

  • result
    Type: System.Double%
    When this method returns, contains a double-precision floating-point number equivalent to the numeric value or symbol contained in s, if the conversion succeeded, or zero if the conversion failed. The conversion fails if the s parameter is nulla null reference (Nothing in Visual Basic), is not in a format compliant with style, represents a number less than MinValue or greater than MaxValue, or if style is not a valid combination of NumberStyles enumerated constants. This parameter is passed uninitialized.

Return Value

Type: System.Boolean
true if s was converted successfully; otherwise, false.

Exceptions

Exception Condition
ArgumentException

style is not a NumberStyles value.

-or-

style includes the NumberStyles.AllowHexSpecifier value.

Remarks

The TryParse method is like the Parse(String, NumberStyles, IFormatProvider) method, except this method does not throw an exception if the conversion fails. If the conversion succeeds, the return value is true and the result parameter is set to the outcome of the conversion. If the conversion fails, the return value is false and the result parameter is set to zero. This eliminates the need to use exception handling to test for a FormatException in the event that s is invalid and cannot be successfully parsed.

The style parameter defines the allowable format of 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 indicated by provider. In addition, depending on the value of style, the s parameter may include the following elements:

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

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

Element

Description

ws

Optional white space. White space can appear at the beginning of s if style includes the NumberStyles.AllowLeadingWhite flag. 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 or NumberFormatInfo.CurrencyPositivePattern properties of the NumberFormatInfo object returned by the IFormatProvider.GetFormat method of the provider parameter. The currency symbol can appear in s if style includes the NumberStyles.AllowCurrencySymbol flag.

sign

An optional sign. 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. Integral-digits can be absent if there are fractional-digits.

,

A culture-specific thousands separator symbol. The current culture's thousands 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 s can represent a number using exponential 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 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 . and fractional-digits elements.

AllowExponent

The s parameter can also use exponential notation. This flag by itself supports values in the form integral-digitsEexponential-digits; additional flags are needed to successfully parse strings in exponential notation 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 , element.

AllowCurrencySymbol

The $ element.

Currency

All. The s parameter 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 . symbol. The s parameter can also use exponential notation.

Number

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

Any

All styles, except s cannot represent a hexadecimal number.

The provider parameter is a IFormatProvider implementation, such as a NumberFormatInfo or CultureInfo object. The provider parameter supplies culture-specific information used in parsing. If provider is nulla null reference (Nothing in Visual Basic) or a NumberFormatInfo object cannot be obtained, the format information for the current culture is used.

The conversion fails if the s parameter is nulla null reference (Nothing in Visual Basic) or not a numeric value, the provider parameter does not yield a NumberFormatInfo object, or the style parameter is not a combination of bit flags from the NumberStyles enumeration.

Ordinarily, if you pass the Double.TryParse 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
Dim number As Double

value = Double.MinValue.ToString()
If Double.TryParse(value, number) Then
   outputBlock.Text += number.ToString() + vbCrLf
Else
   outputBlock.Text += String.Format("{0} is outside the range of a Double.", _
                     value) + vbCrLf
End If

value = Double.MaxValue.ToString()
If Double.TryParse(value, number) Then
   outputBlock.Text += number.ToString() + vbCrLf
Else
   outputBlock.Text += String.Format("{0} is outside the range of a Double.", _
                     value) + vbCrLf
End If
' 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;
double number;

value = Double.MinValue.ToString();
if (Double.TryParse(value, out number))
   outputBlock.Text += number.ToString() + "\n";
else
   outputBlock.Text += String.Format("{0} is outside the range of a Double.\n", 
                     value);

value = Double.MaxValue.ToString();
if (Double.TryParse(value, out number))
   outputBlock.Text += number.ToString() + "\n";
else
   outputBlock.Text += String.Format("{0} is outside the range of a Double.\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 demonstrates the use of the Double.TryParse(String, NumberStyles, IFormatProvider, Double%) method to parse the string representation of numbers that have a particular style and are formatted using the conventions of a particular culture.

Dim value As String
Dim style As NumberStyles
Dim culture As CultureInfo
Dim number As Double

' Parse currency value using en-GB culture.
value = "£1,097.63"
style = NumberStyles.Number Or NumberStyles.AllowCurrencySymbol
culture = New CultureInfo("en-GB")
If Double.TryParse(value, style, culture, number) Then
   outputBlock.Text += String.Format("Converted '{0}' to {1}.", value, number) & vbCrLf
Else
   outputBlock.Text += String.Format("Unable to convert '{0}'.", value) & vbCrLf
End If
' Displays: 
'       Converted '?1,097.63' to 1097.63.

value = "1345,978"
style = NumberStyles.AllowDecimalPoint
culture = New CultureInfo("fr-FR")
If Double.TryParse(value, style, culture, number) Then
   outputBlock.Text += String.Format("Converted '{0}' to {1}.", value, number) & vbCrLf
Else
   outputBlock.Text += String.Format("Unable to convert '{0}'.", value) & vbCrLf
End If
' Displays:
'       Converted '1345,978' to 1345.978.

value = "1.345,978"
style = NumberStyles.AllowDecimalPoint Or NumberStyles.AllowThousands
culture = New CultureInfo("es-ES")
If Double.TryParse(value, style, culture, number) Then
   outputBlock.Text += String.Format("Converted '{0}' to {1}.", value, number) & vbCrLf
Else
   outputBlock.Text += String.Format("Unable to convert '{0}'.", value) & vbCrLf
End If
' Displays: 
'       Converted '1.345,978' to 1345.978.

value = "1 345,978"
If Double.TryParse(value, style, culture, number) Then
   outputBlock.Text += String.Format("Converted '{0}' to {1}.", value, number) & vbCrLf
Else
   outputBlock.Text += String.Format("Unable to convert '{0}'.", value) & vbCrLf
End If
' Displays:
'       Unable to convert '1 345,978'.
string value;
NumberStyles style;
CultureInfo culture;
double number;

// Parse currency value using en-GB culture.
value = "�1,097.63";
style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
culture = new CultureInfo("en-GB");
if (Double.TryParse(value, style, culture, out number))
   outputBlock.Text += String.Format("Converted '{0}' to {1}.\n", value, number);
else
   outputBlock.Text += String.Format("Unable to convert '{0}'.\n", value);
// Displays: 
//       Converted '�1,097.63' to 1097.63.

value = "1345,978";
style = NumberStyles.AllowDecimalPoint;
culture = new CultureInfo("fr-FR");
if (Double.TryParse(value, style, culture, out number))
   outputBlock.Text += String.Format("Converted '{0}' to {1}.\n", value, number);
else
   outputBlock.Text += String.Format("Unable to convert '{0}'.\n", value);
// Displays:
//       Converted '1345,978' to 1345.978.

value = "1.345,978";
style = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands;
culture = new CultureInfo("es-ES");
if (Double.TryParse(value, style, culture, out number))
   outputBlock.Text += String.Format("Converted '{0}' to {1}.\n", value, number);
else
   outputBlock.Text += String.Format("Unable to convert '{0}'.\n", value);
// Displays: 
//       Converted '1.345,978' to 1345.978.

value = "1 345,978";
if (Double.TryParse(value, style, culture, out number))
   outputBlock.Text += String.Format("Converted '{0}' to {1}.\n", value, number);
else
   outputBlock.Text += String.Format("Unable to convert '{0}'.\n", value);
// Displays:
//       Unable to convert '1 345,978'.

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.