Επεξεργασία

Κοινή χρήση μέσω


Double.TryParse Method

Definition

Converts the string representation of a number to its double-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed.

Overloads

TryParse(String, IFormatProvider, Double)

Tries to parse a string into a value.

TryParse(ReadOnlySpan<Char>, Double)

Converts the span 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.

TryParse(String, Double)

Converts the string representation of a number to its double-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed.

TryParse(ReadOnlySpan<Byte>, IFormatProvider, Double)

Tries to parse a span of UTF-8 characters into a value.

TryParse(ReadOnlySpan<Char>, IFormatProvider, Double)

Tries to parse a span of characters into a value.

TryParse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider, Double)

Tries to parse a span of UTF-8 characters into a value.

TryParse(ReadOnlySpan<Byte>, Double)

Tries to convert a UTF-8 character span containing the string representation of a number to its double-precision floating-point number equivalent.

TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Double)

Converts a character span containing 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.

TryParse(String, NumberStyles, IFormatProvider, Double)

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.

Remarks

In .NET Core 3.0 and later, values that are too large to represent are rounded to PositiveInfinity or NegativeInfinity as required by the IEEE 754 specification. In prior versions, including .NET Framework, parsing a value that was too large to represent resulted in failure.

TryParse(String, IFormatProvider, Double)

Source:
Double.cs
Source:
Double.cs
Source:
Double.cs

Tries to parse a string into a value.

public:
 static bool TryParse(System::String ^ s, IFormatProvider ^ provider, [Runtime::InteropServices::Out] double % result) = IParsable<double>::TryParse;
public static bool TryParse (string? s, IFormatProvider? provider, out double result);
static member TryParse : string * IFormatProvider * double -> bool
Public Shared Function TryParse (s As String, provider As IFormatProvider, ByRef result As Double) As Boolean

Parameters

s
String

The string to parse.

provider
IFormatProvider

An object that provides culture-specific formatting information about s.

result
Double

When this method returns, contains the result of successfully parsing s or an undefined value on failure.

Returns

true if s was successfully parsed; otherwise, false.

Applies to

TryParse(ReadOnlySpan<Char>, Double)

Source:
Double.cs
Source:
Double.cs
Source:
Double.cs

Converts the span 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.

public:
 static bool TryParse(ReadOnlySpan<char> s, [Runtime::InteropServices::Out] double % result);
public static bool TryParse (ReadOnlySpan<char> s, out double result);
static member TryParse : ReadOnlySpan<char> * double -> bool
Public Shared Function TryParse (s As ReadOnlySpan(Of Char), ByRef result As Double) As Boolean

Parameters

s
ReadOnlySpan<Char>

A character span that contains the string representation of the number to convert.

result
Double

When this method returns, contains the double-precision floating-point number equivalent of the numeric value or symbol contained in s parameter, if the conversion succeeded, or zero if the conversion failed. The conversion fails if the s parameter is null or empty. If s is a valid number less than Double.MinValue, result is NegativeInfinity. If s is a valid number greater than Double.MaxValue, result is PositiveInfinity. This parameter is passed uninitialized; any value originally supplied in result will be overwritten.

Returns

true if s was converted successfully; otherwise, false.

Remarks

In .NET Core 3.0 and later, values that are too large to represent are rounded to PositiveInfinity or NegativeInfinity as required by the IEEE 754 specification. In prior versions, including .NET Framework, parsing a value that was too large to represent resulted in failure.

Applies to

TryParse(String, Double)

Source:
Double.cs
Source:
Double.cs
Source:
Double.cs

Converts the string representation of a number to its double-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed.

public:
 static bool TryParse(System::String ^ s, [Runtime::InteropServices::Out] double % result);
public static bool TryParse (string s, out double result);
public static bool TryParse (string? s, out double result);
static member TryParse : string * double -> bool
Public Shared Function TryParse (s As String, ByRef result As Double) As Boolean

Parameters

s
String

A string containing a number to convert.

result
Double

When this method returns, contains the double-precision floating-point number equivalent of the s parameter, if the conversion succeeded, or zero if the conversion failed. The conversion fails if the s parameter is null or Empty or is not a number in a valid format. It also fails on .NET Framework and .NET Core 2.2 and earlier versions if s represents a number less than Double.MinValue or greater than Double.MaxValue. This parameter is passed uninitialized; any value originally supplied in result will be overwritten.

Returns

true if s was converted successfully; otherwise, false.

Examples

The following example uses the TryParse(String, Double) method to convert the string representations of numeric values to Double values. It assumes that en-US is the current culture.

using System;

public class Example
{
   public static void Main()
   {
      string[] values = { "1,643.57", "$1,643.57", "-1.643e6",
                          "-168934617882109132", "123AE6",
                          null, String.Empty, "ABCDEF" };
      double number;

      foreach (var value in values) {
         if (Double.TryParse(value, out number))
            Console.WriteLine("'{0}' --> {1}", value, number);
         else
            Console.WriteLine("Unable to parse '{0}'.", value);
      }
   }
}
// The example displays the following output:
//       '1,643.57' --> 1643.57
//       Unable to parse '$1,643.57'.
//       '-1.643e6' --> -1643000
//       '-168934617882109132' --> -1.68934617882109E+17
//       Unable to parse '123AE6'.
//       Unable to parse ''.
//       Unable to parse ''.
//       Unable to parse 'ABCDEF'.
open System

let values =
    [| "1,643.57"; "$1,643.57"; "-1.643e6"
       "-168934617882109132"; "123AE6"
       null; String.Empty; "ABCDEF" |]

for value in values do
    match Double.TryParse value with
    | true, number ->
        printfn $"'{value}' --> {number}"
    | _ ->
        printfn $"Unable to parse '{value}'."
// The example displays the following output:
//       '1,643.57' --> 1643.57
//       Unable to parse '$1,643.57'.
//       '-1.643e6' --> -1643000
//       '-168934617882109132' --> -1.68934617882109E+17
//       Unable to parse '123AE6'.
//       Unable to parse ''.
//       Unable to parse ''.
//       Unable to parse 'ABCDEF'.
Module Example
   Public Sub Main()
      Dim values() As String = { "1,643.57", "$1,643.57", "-1.643e6", 
                                "-168934617882109132", "123AE6", 
                                Nothing, String.Empty, "ABCDEF" }
      Dim number As Double
      
      For Each value In values
         If Double.TryParse(value, number) Then
            Console.WriteLine("'{0}' --> {1}", value, number)
         Else
            Console.WriteLine("Unable to parse '{0}'.", value)      
         End If   
      Next   
   End Sub
End Module
' The example displays the following output:
'       '1,643.57' --> 1643.57
'       Unable to parse '$1,643.57'.
'       '-1.643e6' --> -1643000
'       '-168934617882109132' --> -1.68934617882109E+17
'       Unable to parse '123AE6'.
'       Unable to parse ''.
'       Unable to parse ''.
'       Unable to parse 'ABCDEF'.

Remarks

In .NET Core 3.0 and later, values that are too large to represent are rounded to PositiveInfinity or NegativeInfinity as required by the IEEE 754 specification. In prior versions, including .NET Framework, parsing a value that was too large to represent resulted in failure.

This overload differs from the Double.Parse(String) method by returning a Boolean value that indicates whether the parse operation succeeded instead of returning the parsed numeric value. It 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 s parameter can contain the current culture's NumberFormatInfo.PositiveInfinitySymbol, NumberFormatInfo.NegativeInfinitySymbol, NumberFormatInfo.NaNSymbol (the string comparison is case-sensitive), or a string of the form:

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

Elements in square brackets are optional. The following table describes each element.

Element Description
ws A series of white-space characters.
sign A negative sign or positive sign symbol.
integral-digits A series of numeric characters 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 group separator symbol.
. A culture-specific decimal point symbol.
fractional-digits A series of numeric characters ranging from 0 to 9 that specify the fractional part of the number.
E An uppercase or lowercase character 'e', that indicates exponential (scientific) notation.
exponential-digits A series of numeric characters ranging from 0 to 9 that specify an exponent.

For more information about numeric formats, see Formatting Types.

The s parameter is interpreted by using a combination of the NumberStyles.Float and NumberStyles.AllowThousands flags. This means that white space and thousands separators are allowed but currency symbols are not. To explicitly define the elements (such as currency symbols, thousands separators, and white space) that can be present in s, use the Double.TryParse(String, NumberStyles, IFormatProvider, Double) method overload.

The s parameter is parsed using the formatting information in a NumberFormatInfo object that is initialized for the current system culture. For more information, see NumberFormatInfo.CurrentInfo. To parse a string using the formatting information of some other specified culture, use the Double.TryParse(String, NumberStyles, IFormatProvider, Double) method overload.

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 Double.MinValue or Double.MaxValue fails to round-trip. On .NET Framework and .NET Core 2.2 and previous versions, it throws an OverflowException. On .NET Core 3.0 and later versions, it returns Double.NegativeInfinity if you attempt to parse MinValue or Double.PositiveInfinity if you attempt to parse MaxValue. The following example provides an illustration.

using System;

public class Example
{
   public static void Main()
   {
      string value;
      double number;

      value = Double.MinValue.ToString();
      if (Double.TryParse(value, out number))
         Console.WriteLine(number);
      else
         Console.WriteLine("{0} is outside the range of a Double.",
                           value);

      value = Double.MaxValue.ToString();
      if (Double.TryParse(value, out number))
         Console.WriteLine(number);
      else
         Console.WriteLine("{0} is outside the range of a Double.",
                           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.
open System

[<EntryPoint>]
let main _ = 
    let value = string Double.MinValue
    match Double.TryParse value with
    | true, number ->
        printfn $"{number}"
    | _ ->
        printfn $"{value} is outside the range of a Double."

    let value = string Double.MaxValue
    match Double.TryParse value with
    | true, number ->
        printfn $"{number}"
    | _ ->
        printfn $"{value} is outside the range of a Double."

    0
// 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.
Module Example
   Public Sub Main()
      Dim value As String
      Dim number As Double
      
      value = Double.MinValue.ToString()
      If Double.TryParse(value, number) Then
         Console.WriteLine(number)
      Else
         Console.WriteLine("{0} is outside the range of a Double.", _
                           value)
      End If
      
      value = Double.MaxValue.ToString()
      If Double.TryParse(value, number) Then
         Console.WriteLine(number)
      Else
         Console.WriteLine("{0} is outside the range of a Double.", _
                           value)
      End If
   End Sub
End Module
' 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.

On .NET Framework and .NET Core 2.2 and earlier versions, if s is out of range of the Double data type, the TryParse(String, Double) method throws an OverflowException.

On .NET Core 3.0 and later versions, no exception is thrown when s is out of range of the Double data type. In most cases, the TryParse(String, Double) method calculates a result of Double.PositiveInfinity or Double.NegativeInfinity. However, there is a small set of values that are considered to be closer to the maximum or minimum values of Double than to positive or negative infinity. In those cases, the method calculates a result of Double.MaxValue or Double.MinValue.

If a separator is encountered in the s parameter during a parse operation, and the 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.

See also

Applies to

TryParse(ReadOnlySpan<Byte>, IFormatProvider, Double)

Source:
Double.cs
Source:
Double.cs

Tries to parse a span of UTF-8 characters into a value.

public:
 static bool TryParse(ReadOnlySpan<System::Byte> utf8Text, IFormatProvider ^ provider, [Runtime::InteropServices::Out] double % result) = IUtf8SpanParsable<double>::TryParse;
public static bool TryParse (ReadOnlySpan<byte> utf8Text, IFormatProvider? provider, out double result);
static member TryParse : ReadOnlySpan<byte> * IFormatProvider * double -> bool
Public Shared Function TryParse (utf8Text As ReadOnlySpan(Of Byte), provider As IFormatProvider, ByRef result As Double) As Boolean

Parameters

utf8Text
ReadOnlySpan<Byte>

The span of UTF-8 characters to parse.

provider
IFormatProvider

An object that provides culture-specific formatting information about utf8Text.

result
Double

On return, contains the result of successfully parsing utf8Text or an undefined value on failure.

Returns

true if utf8Text was successfully parsed; otherwise, false.

Applies to

TryParse(ReadOnlySpan<Char>, IFormatProvider, Double)

Source:
Double.cs
Source:
Double.cs
Source:
Double.cs

Tries to parse a span of characters into a value.

public:
 static bool TryParse(ReadOnlySpan<char> s, IFormatProvider ^ provider, [Runtime::InteropServices::Out] double % result) = ISpanParsable<double>::TryParse;
public static bool TryParse (ReadOnlySpan<char> s, IFormatProvider? provider, out double result);
static member TryParse : ReadOnlySpan<char> * IFormatProvider * double -> bool
Public Shared Function TryParse (s As ReadOnlySpan(Of Char), provider As IFormatProvider, ByRef result As Double) As Boolean

Parameters

s
ReadOnlySpan<Char>

The span of characters to parse.

provider
IFormatProvider

An object that provides culture-specific formatting information about s.

result
Double

When this method returns, contains the result of successfully parsing s, or an undefined value on failure.

Returns

true if s was successfully parsed; otherwise, false.

Applies to

TryParse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider, Double)

Source:
Double.cs
Source:
Double.cs

Tries to parse a span of UTF-8 characters into a value.

public:
 static bool TryParse(ReadOnlySpan<System::Byte> utf8Text, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] double % result) = System::Numerics::INumberBase<double>::TryParse;
public static bool TryParse (ReadOnlySpan<byte> utf8Text, System.Globalization.NumberStyles style, IFormatProvider? provider, out double result);
static member TryParse : ReadOnlySpan<byte> * System.Globalization.NumberStyles * IFormatProvider * double -> bool
Public Shared Function TryParse (utf8Text As ReadOnlySpan(Of Byte), style As NumberStyles, provider As IFormatProvider, ByRef result As Double) As Boolean

Parameters

utf8Text
ReadOnlySpan<Byte>

The span of UTF-8 characters to parse.

style
NumberStyles

A bitwise combination of number styles that can be present in utf8Text.

provider
IFormatProvider

An object that provides culture-specific formatting information about utf8Text.

result
Double

On return, contains the result of successfully parsing utf8Text or an undefined value on failure.

Returns

true if utf8Text was successfully parsed; otherwise, false.

Applies to

TryParse(ReadOnlySpan<Byte>, Double)

Source:
Double.cs
Source:
Double.cs

Tries to convert a UTF-8 character span containing the string representation of a number to its double-precision floating-point number equivalent.

public:
 static bool TryParse(ReadOnlySpan<System::Byte> utf8Text, [Runtime::InteropServices::Out] double % result);
public static bool TryParse (ReadOnlySpan<byte> utf8Text, out double result);
static member TryParse : ReadOnlySpan<byte> * double -> bool
Public Shared Function TryParse (utf8Text As ReadOnlySpan(Of Byte), ByRef result As Double) As Boolean

Parameters

utf8Text
ReadOnlySpan<Byte>

A read-only UTF-8 character span that contains the number to convert.

result
Double

When this method returns, contains a double-precision floating-point number equivalent of the numeric value or symbol contained in utf8Text if the conversion succeeded or zero if the conversion failed. The conversion fails if the utf8Text is Empty or is not in a valid format. This parameter is passed uninitialized; any value originally supplied in result will be overwritten.

Returns

true if utf8Text was converted successfully; otherwise, false.

Applies to

TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Double)

Source:
Double.cs
Source:
Double.cs
Source:
Double.cs

Converts a character span containing 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.

public:
 static bool TryParse(ReadOnlySpan<char> s, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] double % result);
public:
 static bool TryParse(ReadOnlySpan<char> s, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] double % result) = System::Numerics::INumberBase<double>::TryParse;
public static bool TryParse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style, IFormatProvider? provider, out double result);
public static bool TryParse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style, IFormatProvider provider, out double result);
static member TryParse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider * double -> bool
Public Shared Function TryParse (s As ReadOnlySpan(Of Char), style As NumberStyles, provider As IFormatProvider, ByRef result As Double) As Boolean

Parameters

s
ReadOnlySpan<Char>

A read-only character span that contains the number to convert.

style
NumberStyles

A bitwise combination of NumberStyles values that indicates the permitted format of s. A typical value to specify is Float combined with AllowThousands.

provider
IFormatProvider

An object that supplies culture-specific formatting information about s.

result
Double

When this method returns and if the conversion succeeded, contains a double-precision floating-point number equivalent of the numeric value or symbol contained in s. Contains zero if the conversion failed. The conversion fails if the s parameter is null, an empty character span, or not a number in a format compliant with style. If s is a valid number less than Double.MinValue, result is NegativeInfinity. If s is a valid number greater than Double.MaxValue, result is PositiveInfinity. This parameter is passed uninitialized; any value originally supplied in result will be overwritten.

Returns

true if s was converted successfully; otherwise, false.

Remarks

In .NET Core 3.0 and later, values that are too large to represent are rounded to PositiveInfinity or NegativeInfinity as required by the IEEE 754 specification. In prior versions, including .NET Framework, parsing a value that was too large to represent resulted in failure.

Applies to

TryParse(String, NumberStyles, IFormatProvider, Double)

Source:
Double.cs
Source:
Double.cs
Source:
Double.cs

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.

public:
 static bool TryParse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] double % result);
public:
 static bool TryParse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] double % result) = System::Numerics::INumberBase<double>::TryParse;
public static bool TryParse (string s, System.Globalization.NumberStyles style, IFormatProvider provider, out double result);
public static bool TryParse (string? s, System.Globalization.NumberStyles style, IFormatProvider? provider, out double result);
static member TryParse : string * System.Globalization.NumberStyles * IFormatProvider * double -> bool
Public Shared Function TryParse (s As String, style As NumberStyles, provider As IFormatProvider, ByRef result As Double) As Boolean

Parameters

s
String

A string containing a number to convert.

style
NumberStyles

A bitwise combination of NumberStyles values that indicates the permitted format of s. A typical value to specify is Float combined with AllowThousands.

provider
IFormatProvider

An IFormatProvider that supplies culture-specific formatting information about s.

result
Double

When this method returns, contains a double-precision floating-point number equivalent of 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 null or Empty or is not in a format compliant with style, or if style is not a valid combination of NumberStyles enumeration constants. It also fails on .NET Framework or .NET Core 2.2 and earlier versions if s represents a number less than SByte.MinValue or greater than SByte.MaxValue. This parameter is passed uninitialized; any value originally supplied in result will be overwritten.

Returns

true if s was converted successfully; otherwise, false.

Exceptions

style is not a NumberStyles value.

-or-

style includes the AllowHexSpecifier value.

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.

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 = CultureInfo.CreateSpecificCulture("en-GB");
if (Double.TryParse(value, style, culture, out number))
   Console.WriteLine("Converted '{0}' to {1}.", value, number);
else
   Console.WriteLine("Unable to convert '{0}'.", value);
// Displays:
//       Converted '£1,097.63' to 1097.63.

value = "1345,978";
style = NumberStyles.AllowDecimalPoint;
culture = CultureInfo.CreateSpecificCulture("fr-FR");
if (Double.TryParse(value, style, culture, out number))
   Console.WriteLine("Converted '{0}' to {1}.", value, number);
else
   Console.WriteLine("Unable to convert '{0}'.", value);
// Displays:
//       Converted '1345,978' to 1345.978.

value = "1.345,978";
style = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands;
culture = CultureInfo.CreateSpecificCulture("es-ES");
if (Double.TryParse(value, style, culture, out number))
   Console.WriteLine("Converted '{0}' to {1}.", value, number);
else
   Console.WriteLine("Unable to convert '{0}'.", value);
// Displays:
//       Converted '1.345,978' to 1345.978.

value = "1 345,978";
if (Double.TryParse(value, style, culture, out number))
   Console.WriteLine("Converted '{0}' to {1}.", value, number);
else
   Console.WriteLine("Unable to convert '{0}'.", value);
// Displays:
//       Unable to convert '1 345,978'.
// Parse currency value using en-GB culture.
let value = "£1,097.63"
let style = NumberStyles.Number ||| NumberStyles.AllowCurrencySymbol
let culture = CultureInfo.CreateSpecificCulture "en-GB"
match Double.TryParse(value, style, culture) with
| true, number ->
    printfn $"Converted '{value}' to {number}."
| _ ->
    printfn $"Unable to convert '{value}'."
// Displays:
//       Converted '£1,097.63' to 1097.63.

let value = "1345,978"
let style = NumberStyles.AllowDecimalPoint
let culture = CultureInfo.CreateSpecificCulture "fr-FR"
match Double.TryParse(value, style, culture) with
| true, number ->
    printfn $"Converted '{value}' to {number}."
| _ ->
    printfn $"Unable to convert '{value}'."
// Displays:
//       Converted '1345,978' to 1345.978.

let value = "1.345,978"
let style = NumberStyles.AllowDecimalPoint ||| NumberStyles.AllowThousands
let culture = CultureInfo.CreateSpecificCulture("es-ES")
match Double.TryParse(value, style, culture) with
| true, number ->
    printfn $"Converted '{value}' to {number}."
| _ ->
    printfn $"Unable to convert '{value}'."
// Displays:
//       Converted '1.345,978' to 1345.978.

let value = "1 345,978"
match Double.TryParse(value, style, culture) with
| true, number ->
    printfn $"Converted '{value}' to {number}."
| _ ->
    printfn $"Unable to convert '{value}'."
// Displays:
//       Unable to convert '1 345,978'.
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 = CultureInfo.CreateSpecificCulture("en-GB")
If Double.TryParse(value, style, culture, number) Then
   Console.WriteLine("Converted '{0}' to {1}.", value, number)
Else
   Console.WriteLine("Unable to convert '{0}'.", value)
End If    
' Displays: 
'       Converted '£1,097.63' to 1097.63.

value = "1345,978"
style = NumberStyles.AllowDecimalPoint
culture = CultureInfo.CreateSpecificCulture("fr-FR")
If Double.TryParse(value, style, culture, number) Then
   Console.WriteLine("Converted '{0}' to {1}.", value, number)
Else
   Console.WriteLine("Unable to convert '{0}'.", value)
End If    
' Displays:
'       Converted '1345,978' to 1345.978.

value = "1.345,978"
style = NumberStyles.AllowDecimalPoint Or NumberStyles.AllowThousands
culture = CultureInfo.CreateSpecificCulture("es-ES")
If Double.TryParse(value, style, culture, number) Then
   Console.WriteLine("Converted '{0}' to {1}.", value, number)
Else
   Console.WriteLine("Unable to convert '{0}'.", value)
End If    
' Displays: 
'       Converted '1.345,978' to 1345.978.

value = "1 345,978"
If Double.TryParse(value, style, culture, number) Then
   Console.WriteLine("Converted '{0}' to {1}.", value, number)
Else
   Console.WriteLine("Unable to convert '{0}'.", value)
End If    
' Displays:
'       Unable to convert '1 345,978'.

Remarks

In .NET Core 3.0 and later, values that are too large to represent are rounded to PositiveInfinity or NegativeInfinity as required by the IEEE 754 specification. In prior versions, including .NET Framework, parsing a value that was too large to represent resulted in failure.

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.

Note

Any terminating NUL (U+0000) characters in s are ignored by the parsing operation, regardless of the value of the style argument.

A string with digits only (which corresponds to the NumberStyles.None style) always parses successfully if it is in the range of the Double type. 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 null or a NumberFormatInfo object cannot be obtained, the format information for the current culture is used.

The conversion fails if the s parameter is null 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 Double.MinValue or Double.MaxValue fails to round-trip. On .NET Framework and .NET Core 2.2 and previous versions, it throws an OverflowException. On .NET Core 3.0 and later versions, it returns Double.NegativeInfinity if you attempt to parse MinValue or Double.PositiveInfinity if you attempt to parse MaxValue. The following example provides an illustration.

using System;

public class Example
{
   public static void Main()
   {
      string value;
      double number;

      value = Double.MinValue.ToString();
      if (Double.TryParse(value, out number))
         Console.WriteLine(number);
      else
         Console.WriteLine("{0} is outside the range of a Double.",
                           value);

      value = Double.MaxValue.ToString();
      if (Double.TryParse(value, out number))
         Console.WriteLine(number);
      else
         Console.WriteLine("{0} is outside the range of a Double.",
                           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.
open System

[<EntryPoint>]
let main _ = 
    let value = string Double.MinValue
    match Double.TryParse value with
    | true, number ->
        printfn $"{number}"
    | _ ->
        printfn $"{value} is outside the range of a Double."

    let value = string Double.MaxValue
    match Double.TryParse value with
    | true, number ->
        printfn $"{number}"
    | _ ->
        printfn $"{value} is outside the range of a Double."

    0
// 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.
Module Example
   Public Sub Main()
      Dim value As String
      Dim number As Double
      
      value = Double.MinValue.ToString()
      If Double.TryParse(value, number) Then
         Console.WriteLine(number)
      Else
         Console.WriteLine("{0} is outside the range of a Double.", _
                           value)
      End If
      
      value = Double.MaxValue.ToString()
      If Double.TryParse(value, number) Then
         Console.WriteLine(number)
      Else
         Console.WriteLine("{0} is outside the range of a Double.", _
                           value)
      End If
   End Sub
End Module
' 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.

On .NET Framework and .NET Core 2.2 and earlier versions, if s is out of range of the Double data type, the Double.TryParse(String, NumberStyles, IFormatProvider, Double) method throws an OverflowException.

On .NET Core 3.0 and later versions, no exception is thrown when s is out of range of the Double data type. In most cases, the Double.TryParse(String, NumberStyles, IFormatProvider, Double) method calculates a result of Double.PositiveInfinity or Double.NegativeInfinity. However, there is a small set of values that are considered to be closer to the maximum or minimum values of Double than to positive or negative infinity. In those cases, the method calculates a result of Double.MaxValue or Double.MinValue.

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.

See also

Applies to