通过


Double.TryParse 方法

定义

将数字的字符串表示形式转换为等效的双精度浮点数。 返回值指示转换是成功还是失败。

重载

名称 说明
TryParse(String, IFormatProvider, Double)

尝试将字符串分析为值。

TryParse(ReadOnlySpan<Char>, Double)

将指定样式和区域性特定格式的数字的跨度表示形式转换为其等效的双精度浮点数。 返回值指示转换是成功还是失败。

TryParse(String, Double)

将数字的字符串表示形式转换为等效的双精度浮点数。 返回值指示转换是成功还是失败。

TryParse(ReadOnlySpan<Byte>, IFormatProvider, Double)

尝试将 UTF-8 字符的范围分析为值。

TryParse(ReadOnlySpan<Char>, IFormatProvider, Double)

尝试将字符范围分析为值。

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

尝试将 UTF-8 字符的范围分析为值。

TryParse(ReadOnlySpan<Byte>, Double)

尝试将包含数字字符串表示形式的 UTF-8 字符范围转换为其等效的双精度浮点数。

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

将包含指定样式和区域性特定格式的数字的字符串表示形式的字符范围转换为其等效的双精度浮点数。 返回值指示转换是成功还是失败。

TryParse(String, NumberStyles, IFormatProvider, Double)

将指定样式和区域性特定格式的数字的字符串表示形式转换为等效的双精度浮点数。 返回值指示转换是成功还是失败。

注解

在 .NET Core 3.0 及更高版本中,无法表示的值舍 PositiveInfinity 入到 NegativeInfinity IEEE 754 规范或根据需要舍入。 在早期版本中(包括 .NET Framework)中,分析的值太大而无法表示导致失败。

TryParse(String, IFormatProvider, Double)

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

尝试将字符串分析为值。

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

参数

s
String

要分析的字符串。

provider
IFormatProvider

一个对象,提供有关区域性特定的格式设置信息 s

result
Double

此方法返回时,包含成功分析 s 的结果或失败时未定义的值。

返回

如果已成功分析,则为 0;否则为

适用于

TryParse(ReadOnlySpan<Char>, Double)

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

将指定样式和区域性特定格式的数字的跨度表示形式转换为其等效的双精度浮点数。 返回值指示转换是成功还是失败。

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

参数

s
ReadOnlySpan<Char>

包含要转换的数字的字符串表示形式的字符范围。

result
Double

此方法返回时,如果转换成功,则包含与参数中包含的 s 数值或符号等效的双精度浮点数;如果转换失败,则包含零。 如果参数为s空,null则转换失败。 如果 s 有效数字小于 Double.MinValueresult 则为 NegativeInfinity. 如果 s 有效数字大于 Double.MaxValueresult 则为 PositiveInfinity. 此参数未初始化传递;最初提供 result 的任何值将被覆盖。

返回

true 如果 s 已成功转换,则为 :否则为 false

注解

在 .NET Core 3.0 及更高版本中,无法表示的值舍 PositiveInfinity 入到 NegativeInfinity IEEE 754 规范或根据需要舍入。 在早期版本中(包括 .NET Framework)中,分析的值太大而无法表示导致失败。

适用于

TryParse(String, Double)

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

将数字的字符串表示形式转换为等效的双精度浮点数。 返回值指示转换是成功还是失败。

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

参数

s
String

包含要转换的数字的字符串。

result
Double

此方法返回时,如果转换成功,则包含与参数等效的 s 双精度浮点数;如果转换失败,则包含零。 如果 s 参数为 nullEmpty 不是有效格式的数字,则转换失败。 如果s表示的数字小于 Double.MinValue 或大于 Double.MaxValue,则它在 .NET Framework 上也会失败。 此参数未初始化传递;最初提供 result 的任何值将被覆盖。

返回

true 如果 s 已成功转换,则为 :否则为 false

示例

下面的示例使用 TryParse(String, Double) 该方法将数值的字符串表示形式转换为 Double 值。 它假定 en-US 是当前区域性。

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'.

注解

在 .NET Core 3.0 及更高版本中,无法表示的值舍 PositiveInfinity 入到 NegativeInfinity IEEE 754 规范或根据需要舍入。 在早期版本中(包括 .NET Framework)中,分析的值太大而无法表示导致失败。

此重载与方法不同 Double.Parse(String) ,方法是返回一个布尔值,该值指示分析操作是否成功,而不是返回已分析的数值。 它无需使用异常处理来测试 FormatException 无效且无法成功分析的事件 s

s 参数可以包含当前区域性的 NumberFormatInfo.PositiveInfinitySymbolNumberFormatInfo.NegativeInfinitySymbolNumberFormatInfo.NaNSymbol 符号。 此字符串比较在 .NET Core 3.0 及更高版本中不区分大小写,但在早期版本(包括 .NET Framework)中区分大小写。 该 s 参数也可以是窗体的字符串:

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

方括号中的元素是可选的。 下表描述了每个元素。

元素 描述
ws 一系列空白字符。
签名 负号或正符号。
整型数字 一系列数字字符,范围从 0 到 9,用于指定数字的整部分。 如果存在小数位数,则可以缺少整型数字。
区域性特定的组分隔符符号。
. 区域性特定的小数点符号。
fractional-digits 一系列数字字符,范围从 0 到 9,用于指定数字的小数部分。
E 一个大写或小写字符“e”,指示指数(科学)表示法。
exponential-digits 一系列数字字符,范围从 0 到 9,用于指定指数。

有关数字格式的详细信息,请参阅 “格式设置类型”。

参数s是使用和NumberStyles.Float标志的组合来解释的NumberStyles.AllowThousands。 这意味着允许空格和数千个分隔符,但货币符号不是。 若要显式定义可以存在的 s元素(如货币符号、千位分隔符和空格),请使用 Double.TryParse(String, NumberStyles, IFormatProvider, Double) 方法重载。

s 参数使用为当前系统区域性初始化的对象中的 NumberFormatInfo 格式设置信息进行分析。 有关详细信息,请参阅 NumberFormatInfo.CurrentInfo。 若要使用其他指定区域性的格式设置信息分析字符串,请使用 Double.TryParse(String, NumberStyles, IFormatProvider, Double) 方法重载。

通常,如果通过调用Double.TryParse该方法传递Double.ToString方法创建的字符串,则返回原始Double值。 但是,由于精度损失,值可能不相等。 此外,尝试分析任一或Double.MinValueDouble.MaxValue未能往返的字符串表示形式。 在 .NET Framework 上,它会引发一个 OverflowException. 在 .NET Core 3.0 及更高版本中,如果尝试分析,或者Double.PositiveInfinity尝试分析MaxValue,它将返回Double.NegativeInfinityMinValue 以下示例提供了一个插图。

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.

在 .NET Framework 上,如果 s 数据类型的范围 Double 不足,该方法 TryParse(String, Double) 将引发一个 OverflowException

在 .NET Core 3.0 及更高版本中,当数据类型范围s不足时Double,不会引发异常。 在大多数情况下,该方法 TryParse(String, Double) 计算结果 Double.PositiveInfinityDouble.NegativeInfinity。 但是,有一小组值被认为离最大值或最小值 Double 更接近正或负无穷大。 在这些情况下,该方法计算结果 Double.MaxValueDouble.MinValue

如果在分析操作期间在参数中 s 遇到分隔符,并且小数分隔符和组分隔符相同,则分析操作假定分隔符是小数分隔符,而不是组分隔符。 有关分隔符的详细信息,请参阅CurrencyDecimalSeparatorNumberDecimalSeparatorCurrencyGroupSeparatorNumberGroupSeparator

另请参阅

适用于

TryParse(ReadOnlySpan<Byte>, IFormatProvider, Double)

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

尝试将 UTF-8 字符的范围分析为值。

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

参数

utf8Text
ReadOnlySpan<Byte>

要分析的 UTF-8 字符的范围。

provider
IFormatProvider

一个对象,提供有关区域性特定的格式设置信息 utf8Text

result
Double

返回时,包含成功分析 utf8Text 的结果或失败时未定义的值。

返回

如果已成功分析,则为 0;否则为

适用于

TryParse(ReadOnlySpan<Char>, IFormatProvider, Double)

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

尝试将字符范围分析为值。

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

参数

s
ReadOnlySpan<Char>

要分析的字符范围。

provider
IFormatProvider

一个对象,提供有关区域性特定的格式设置信息 s

result
Double

此方法返回时,包含成功分析 s的结果或失败时未定义的值。

返回

如果已成功分析,则为 0;否则为

适用于

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

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

尝试将 UTF-8 字符的范围分析为值。

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

参数

utf8Text
ReadOnlySpan<Byte>

要分析的 UTF-8 字符的范围。

style
NumberStyles

可以存在的 utf8Text数字样式的按位组合。

provider
IFormatProvider

一个对象,提供有关区域性特定的格式设置信息 utf8Text

result
Double

返回时,包含成功分析 utf8Text 的结果或失败时未定义的值。

返回

如果已成功分析,则为 0;否则为

适用于

TryParse(ReadOnlySpan<Byte>, Double)

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

尝试将包含数字字符串表示形式的 UTF-8 字符范围转换为其等效的双精度浮点数。

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

参数

utf8Text
ReadOnlySpan<Byte>

包含要转换的数字的只读 UTF-8 字符范围。

result
Double

此方法返回时,如果转换成功或转换失败,则包含与数值或符号等效 utf8Text 的双精度浮点数。 如果 utf8Text 转换格式 Empty 无效,则转换失败。 此参数未初始化传递;将覆盖最初在结果中提供的任何值。

返回

true 如果 utf8Text 已成功转换,则为 :否则为 false

适用于

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

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

将包含指定样式和区域性特定格式的数字的字符串表示形式的字符范围转换为其等效的双精度浮点数。 返回值指示转换是成功还是失败。

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, [Runtime::InteropServices::Out] double % result);
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

参数

s
ReadOnlySpan<Char>

包含要转换的数字的只读字符范围。

style
NumberStyles

指示允许的格式NumberStyles的值的s按位组合。 要指定的 Float 典型值与 AllowThousands.

provider
IFormatProvider

一个对象,提供有关区域性特定的格式设置信息 s

result
Double

此方法返回时,如果转换成功,则包含与数值或符号中包含的 s数值或符号等效的双精度浮点数。 如果转换失败,则包含零。 如果 s 参数为 null空字符范围,或者不符合格式 style的数字,则转换失败。 如果 s 有效数字小于 Double.MinValueresult 则为 NegativeInfinity. 如果 s 有效数字大于 Double.MaxValueresult 则为 PositiveInfinity. 此参数未初始化传递;最初提供 result 的任何值将被覆盖。

返回

true 如果 s 已成功转换,则为 :否则为 false

注解

在 .NET Core 3.0 及更高版本中,无法表示的值舍 PositiveInfinity 入到 NegativeInfinity IEEE 754 规范或根据需要舍入。 在早期版本中(包括 .NET Framework)中,分析的值太大而无法表示导致失败。

适用于

TryParse(String, NumberStyles, IFormatProvider, Double)

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

将指定样式和区域性特定格式的数字的字符串表示形式转换为等效的双精度浮点数。 返回值指示转换是成功还是失败。

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

参数

s
String

包含要转换的数字的字符串。

style
NumberStyles

指示允许的格式NumberStyles的值的s按位组合。 要指定的 Float 典型值与 AllowThousands.

provider
IFormatProvider

提供有关 IFormatProvider 区域性的格式化信息 s

result
Double

此方法返回时,如果转换成功,则包含与数值或符号 s等效的双精度浮点数;如果转换失败,则包含零。 如果 s 参数符合 nullEmpty 不符合格式 style,或者 style 不是枚举常量的有效组合 NumberStyles ,则转换失败。 如果s表示小于 SByte.MinValue 或大于 SByte.MaxValue 的数字,则 .NET Framework 也会失败。 此参数未初始化传递;最初提供 result 的任何值将被覆盖。

返回

true 如果 s 已成功转换,则为 :否则为 false

例外

style 不是值 NumberStyles

-或-

style AllowHexSpecifier包括值。

示例

下面的示例演示如何使用 Double.TryParse(String, NumberStyles, IFormatProvider, Double) 该方法分析具有特定样式的数字的字符串表示形式,并使用特定区域性的约定进行格式设置。

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'.

注解

在 .NET Core 3.0 及更高版本中,无法表示的值舍 PositiveInfinity 入到 NegativeInfinity IEEE 754 规范或根据需要舍入。 在早期版本中(包括 .NET Framework)中,分析的值太大而无法表示导致失败。

此方法 TryParse 与该方法类似 Parse(String, NumberStyles, IFormatProvider) ,但此方法在转换失败时不会引发异常。 如果转换成功,则返回值为 true 并将 result 参数设置为转换的结果。 如果转换失败,则返回值为 false ,参数 result 设置为零。 这样就无需使用异常处理来测试 FormatException 无效且无法成功分析的事件 s

style 参数定义参数允许的格式 s ,以便分析操作成功。 它必须是枚举中的 NumberStyles 位标志的组合。 不支持以下 NumberStyles 成员:

参数s可以包含NumberFormatInfo.PositiveInfinitySymbolNumberFormatInfo.NegativeInfinitySymbolNumberFormatInfo.NaNSymbol表示的区域性的provider符号。 此字符串比较在 .NET Core 3.0 及更高版本中不区分大小写,但在早期版本(包括 .NET Framework)中区分大小写。 此外,根据其值 style,参数 s 可能包含以下元素:

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

方括号 ([ 和 ]) 中的元素是可选的。 下表描述了每个元素。

元素 描述
ws 可选空格。 如果s包含style标志,则空白可以出现在开头NumberStyles.AllowLeadingWhite。 如果s包含style标志,则它可以显示在末尾NumberStyles.AllowTrailingWhite
$ 区域性特定的货币符号。 字符串中的位置由NumberFormatInfo.CurrencyNegativePattern参数方法NumberFormatInfo.CurrencyPositivePattern返回NumberFormatInfo的对象或IFormatProvider.GetFormat属性provider定义。 如果s包含标志,则货币符号可以出现在style其中NumberStyles.AllowCurrencySymbol
签名 可选符号。 如果s包含标志,则符号可以出现在标志的style开头,如果包含NumberStyles.AllowLeadingSign标志,则它将显示在标志的sstyleNumberStyles.AllowTrailingSign末尾。 括号可用于 s 指示负值(如果 style 包含 NumberStyles.AllowParentheses 标志)。
整型数字 一系列数字,范围从 0 到 9,用于指定数字的整部分。 如果存在小数位数,则可以缺少整型数字。
区域性特定的千位分隔符符号。 如果包含标志,则当前区域性的千位分隔符可以出现在其中 sstyleNumberStyles.AllowThousands
. 区域性特定的小数点符号。 如果包含标志,则当前区域性的小数点符号可以出现在sstyle其中NumberStyles.AllowDecimalPoint
fractional-digits 一系列数字,范围从 0 到 9,指定数字的小数部分。 如果s包含style标志,则可以显示NumberStyles.AllowDecimalPoint小数位数。
e e 或 E 字符,指示 s 可以使用指数表示法表示数字。 如果样式包含标志,则参数 s 可以表示指数表示法中的 NumberStyles.AllowExponent 数字。
exponential-digits 一系列数字,范围从 0 到 9,用于指定指数。

注意

无论参数的值s如何,分析作都会忽略任何终止 NUL (U+0000) 字符style

仅包含数字(对应于样式)的 NumberStyles.None 字符串在类型范围内 Double 时始终成功分析。 其余 System.Globalization.NumberStyles 成员控制可能但不需要在输入字符串中存在的元素。 下表指示各个 NumberStyles 标志如何影响可能存在的 s元素。

NumberStyles 值 除数字外允许的元素
None 仅限 整型数字 元素。
AllowDecimalPoint 小数位数元素。
AllowExponent s 参数还可以使用指数表示法。 此标志本身支持整数 数字E指数数字形式的值;需要使用其他标志以指数表示法成功分析字符串,这些元素包括正号或负号和小数点符号。
AllowLeadingWhite 开头的 s 元素。
AllowTrailingWhite 末尾的 s 元素
AllowLeadingSign 开头的 s 元素。
AllowTrailingSign 结尾处的 s 元素。
AllowParentheses 括住数值的括号形式的 符号 元素。
AllowThousands 元素
AllowCurrencySymbol 元素 $
Currency 都。 该 s 参数不能表示十六进制数或指数表示法中的数字。
Float 开头或结尾处的 s 元素,符号位于开头s. 符号。s 参数还可以使用指数表示法。
Number wssign千位分隔符(,)和小数点(.)元素。
Any 所有样式,但 s 不能表示十六进制数。

参数 provider 是实现 IFormatProvider ,例如 NumberFormatInfoCultureInfo 对象。 该 provider 参数提供分析中使用的区域性特定信息。 如果provider无法获取或nullNumberFormatInfo无法获取对象,则使用当前区域性的格式信息。

如果 s 参数不是 null 数值, provider 参数不会生成 NumberFormatInfo 对象,或者 style 该参数不是枚举中的 NumberStyles 位标志的组合,则转换失败。

通常,如果通过调用Double.TryParse该方法传递Double.ToString方法创建的字符串,则返回原始Double值。 但是,由于精度损失,值可能不相等。 此外,尝试分析任一或Double.MinValueDouble.MaxValue未能往返的字符串表示形式。 在 .NET Framework 上,它会引发一个 OverflowException. 在 .NET Core 3.0 及更高版本中,如果尝试分析,或者Double.PositiveInfinity尝试分析MaxValue,它将返回Double.NegativeInfinityMinValue 以下示例提供了一个插图。

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.

在 .NET Framework 上,如果 s 数据类型的范围 Double 不足,该方法 Double.TryParse(String, NumberStyles, IFormatProvider, Double) 将引发一个 OverflowException

在 .NET Core 3.0 及更高版本中,当数据类型范围s不足时Double,不会引发异常。 在大多数情况下,该方法 Double.TryParse(String, NumberStyles, IFormatProvider, Double) 计算结果 Double.PositiveInfinityDouble.NegativeInfinity。 但是,有一小组值被认为离最大值或最小值 Double 更接近正或负无穷大。 在这些情况下,该方法计算结果 Double.MaxValueDouble.MinValue

如果在分析操作期间在参数中 s 遇到分隔符,并且适用的货币或数字小数和组分隔符相同,则分析操作假定分隔符是小数分隔符,而不是组分隔符。 有关分隔符的详细信息,请参阅CurrencyDecimalSeparatorNumberDecimalSeparatorCurrencyGroupSeparatorNumberGroupSeparator

另请参阅

适用于