Double.TryParse 方法

定义

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

重载

TryParse(ReadOnlySpan<Char>, IFormatProvider, Double)

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

TryParse(ReadOnlySpan<Char>, Double)

将指定样式和区域性特定格式的数字的范围表示形式转换为它的等效双精度浮点数。 一个指示转换是否成功的返回值。

TryParse(String, Double)

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

TryParse(ReadOnlySpan<Byte>, IFormatProvider, Double)

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

TryParse(String, 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 IEEE NegativeInfinity 754 规范的要求。 在以前的版本中(包括.NET Framework)中,分析太大而无法表示的值会导致失败。

TryParse(ReadOnlySpan<Char>, IFormatProvider, Double)

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

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的结果或失败时的未定义值。

返回

true 如果 s 已成功分析,则为 ;否则为 false

适用于

TryParse(ReadOnlySpan<Char>, Double)

将指定样式和区域性特定格式的数字的范围表示形式转换为它的等效双精度浮点数。 一个指示转换是否成功的返回值。

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 或空,或其格式不符合 style,则转换失败。 如果 style 不是 NumberStyles 枚举常量的有效组合,则转换也会失败。 如果 s 是小于 Double.MinValue 的有效数字, result 则 为 NegativeInfinity。 如果 s 是大于 Double.MaxValue 的有效数字, result 则 为 PositiveInfinity。 此参数未经初始化即进行传递;最初在 result 中提供的任何值都会被覆盖。

返回

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

注解

在 .NET Core 3.0 及更高版本中,太大而无法表示的值将舍入到 PositiveInfinity IEEE NegativeInfinity 754 规范的要求。 在以前的版本中(包括.NET Framework)中,分析太大而无法表示的值会导致失败。

适用于

TryParse(String, Double)

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

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 和 .NET Core 2.2 及更早版本上也会失败。 此参数未经初始化即进行传递;最初在 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 IEEE NegativeInfinity 754 规范的要求。 在以前的版本中(包括.NET Framework)中,分析太大而无法表示的值会导致失败。

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

参数 s 可以包含当前区域性的 NumberFormatInfo.PositiveInfinitySymbolNumberFormatInfo.NegativeInfinitySymbol、、 NumberFormatInfo.NaNSymbol (字符串比较区分大小写) 或格式的字符串:

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

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

元素 说明
ws 一系列空格字符。
sign 负号或正符号。
integral-digits 一系列数字字符,范围从 0 到 9,指定数字的整型部分。 如果有小数位数,则整型数字可能不存在。
, 区域性特定的组分隔符。
. 区域性特定的小数点符号。
fractional-digits 一系列数字字符,范围从 0 到 9,指定数字的小数部分。
E 大写或小写字符“e”,指示指数 (科学) 表示法。
exponential-digits 一系列数字字符,范围从 0 到 9,指定指数。

有关数值格式的详细信息,请参阅 格式设置类型

参数s通过使用 和 NumberStyles.AllowThousands 标志的组合NumberStyles.Float进行解释。 这意味着允许使用空格和数千个分隔符,但不允许使用货币符号。 若要显式定义 (元素,例如货币符号、千位分隔符和空白) 中可能存在 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 和 .NET Core 2.2 及早期版本上,它会引发 OverflowException。 在 .NET Core 3.0 及更高版本中,如果尝试分析或Double.PositiveInfinity尝试分析 MaxValueMinValue ,则返回 Double.NegativeInfinity 。 下面的示例进行了这方面的演示。

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 和 .NET Core 2.2 及更早版本上,如果s数据类型的范围Double外,方法TryParse(String, Double)OverflowException引发 。

在 .NET Core 3.0 及更高版本上,当数据类型范围之外Doubles不会引发异常。 在大多数情况下, TryParse(String, Double) 方法计算 或 Double.NegativeInfinity的结果Double.PositiveInfinity。 但是,有一小部分值被视为更接近最大值或最小值 Double ,而不是正无穷大或负无穷大。 在这些情况下, 方法计算 或 Double.MinValue的结果Double.MaxValue

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

另请参阅

适用于

TryParse(ReadOnlySpan<Byte>, IFormatProvider, Double)

尝试将 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 的结果或失败时未定义的值。

返回

true 如果 utf8Text 已成功分析,则为 ;否则为 false

适用于

TryParse(String, IFormatProvider, Double)

尝试将字符串分析为值。

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 的结果或失败时的未定义值。

返回

true 如果 s 已成功分析,则为 ;否则为 false

适用于

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

尝试将 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 的结果或失败时未定义的值。

返回

true 如果 utf8Text 已成功分析,则为 ;否则为 false

适用于

TryParse(ReadOnlySpan<Byte>, Double)

尝试将包含数字字符串表示形式的 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 数值或符号等效的双精度浮点数;如果转换失败,则包含零。 如果 utf8TextEmpty 或 格式无效,则转换失败。 此参数未经初始化即进行传递;最初在 result 中提供的任何值都会被覆盖。

返回

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

适用于

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

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

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

参数

s
ReadOnlySpan<Char>

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

style
NumberStyles

NumberStyles 值的按位组合,指示 s 的允许格式。 一个用来指定的典型值为 FloatAllowThousands 的组合。

provider
IFormatProvider

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

result
Double

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

返回

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

注解

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

适用于

TryParse(String, NumberStyles, IFormatProvider, Double)

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

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 的允许格式。 一个用来指定的典型值为 FloatAllowThousands 的组合。

provider
IFormatProvider

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

result
Double

当此方法返回时,如果转换成功,则包含与 s 中所包含的数值或符号等效的双精度浮点数;如果转换失败,则包含零。 如果 s 参数为 nullEmpty,或格式不符合 style,或 style 不是 NumberStyles 枚举常量的有效组合,则转换失败。 如果 s 表示的数字小于 SByte.MinValue 或大于 SByte.MaxValue,则它在 .NET Framework 或 .NET Core 2.2 及更早版本上也会失败。 此参数未经初始化即进行传递;最初在 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 IEEE 754 规范要求的 或 NegativeInfinity 。 在以前的版本中(包括 .NET Framework)中,分析太大而无法表示的值会导致失败。

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

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

对于 s 指示provider的区域性, 参数可以包含 NumberFormatInfo.PositiveInfinitySymbolNumberFormatInfo.NegativeInfinitySymbolNumberFormatInfo.NaNSymbol 。 此外,根据 的值 styles 参数可能包括以下元素:

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

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

元素 说明
ws 可选空格。 如果style包含 NumberStyles.AllowLeadingWhite 标志,s则 开头会出现空格。 如果style包含 标志,NumberStyles.AllowTrailingWhite则它可以显示在 的末尾s
$ 区域性特定的货币符号。 它在字符串中的位置由 NumberFormatInfo.CurrencyNegativePattern 参数的 方法provider返回IFormatProvider.GetFormatNumberFormatInfo 对象的 或 NumberFormatInfo.CurrencyPositivePattern 属性定义。 如果style包含 标志,NumberStyles.AllowCurrencySymbol则可以在 中s显示货币符号。
sign 可选符号。 如果包含 标志,则符号可以出现在 的s开头,如果style包含 NumberStyles.AllowTrailingSign 标志,则它可显示在 的末尾sNumberStyles.AllowLeadingSignstyle 如果style包含 标志,NumberStyles.AllowParentheses则可以在 中使用s括号来指示负值。
integral-digits 一系列数字,范围从 0 到 9,指定数字的整数部分。 如果有小数位数,则整数可能不存在。
, 区域性特定的千位分隔符。 如果style包含 NumberStyles.AllowThousands 标志,则当前区域性的千位分隔符可以出现在 中s
. 区域性特定的小数点符号。 如果style包含 NumberStyles.AllowDecimalPoint 标志,则当前区域性的小数点符号可以出现在 中s
fractional-digits 一系列数字,范围从 0 到 9,指定数字的小数部分。 如果style包含 标志,NumberStyles.AllowDecimalPoint则可以在 中s显示小数位数。
e e 或 E 字符,指示 s 可以使用指数表示法表示数字。 如果样式包含 标志,则 s 参数可以表示指数表示法中的 NumberStyles.AllowExponent 数字。
exponential-digits 指定指数的一系列数字,范围为 0 到 9。

注意

分析操作将忽略中 s 任何 (U+0000) 字符的终止 NUL,而不考虑 参数的值 style

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

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

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

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

通常,如果向 方法传递 Double.TryParse 通过调用 Double.ToString 方法创建的字符串,则会返回原始 Double 值。 但是,由于精度损失,这些值可能不相等。 此外,尝试分析 的字符串表示形式 Double.MinValueDouble.MaxValue 无法进行往返。 在 .NET Framework 和 .NET Core 2.2 及早期版本上,它会引发 OverflowException。 在 .NET Core 3.0 及更高版本中,如果尝试分析或Double.PositiveInfinity尝试分析 MaxValueMinValue ,则返回 Double.NegativeInfinity 。 下面的示例进行了这方面的演示。

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 和 .NET Core 2.2 及更早版本上,如果s数据类型的范围Double外,方法Double.TryParse(String, NumberStyles, IFormatProvider, Double)OverflowException引发 。

在 .NET Core 3.0 及更高版本上,当数据类型范围之外Doubles不会引发异常。 在大多数情况下, Double.TryParse(String, NumberStyles, IFormatProvider, Double) 方法计算 或 Double.NegativeInfinity的结果Double.PositiveInfinity。 但是,有一小部分值被视为更接近最大值或最小值 Double ,而不是正无穷大或负无穷大。 在这些情况下, 方法计算 或 Double.MinValue的结果Double.MaxValue

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

另请参阅

适用于