Udostępnij za pośrednictwem


Double.Parse Metoda

Definicja

Konwertuje reprezentację ciągu liczby na równoważną liczbę zmiennoprzecinkową o podwójnej precyzji.

Przeciążenia

Nazwa Opis
Parse(String)

Konwertuje reprezentację ciągu liczby na równoważną liczbę zmiennoprzecinkową o podwójnej precyzji.

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Analizuje zakres znaków UTF-8 w wartość.

Parse(ReadOnlySpan<Char>, IFormatProvider)

Analizuje zakres znaków w wartości.

Parse(String, NumberStyles)

Konwertuje reprezentację ciągu liczby w określonym stylu na równoważnik liczby zmiennoprzecinkowych o podwójnej precyzji.

Parse(String, IFormatProvider)

Konwertuje reprezentację ciągu liczby w określonym formacie specyficznym dla kultury na równoważnik liczby zmiennoprzecinkowych o podwójnej precyzji.

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

Analizuje zakres znaków UTF-8 w wartość.

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Konwertuje zakres znaków zawierający ciąg reprezentujący liczbę w określonym stylu i formacie specyficznym dla kultury na równoważnik liczby zmiennoprzecinkowych o podwójnej precyzji.

Parse(String, NumberStyles, IFormatProvider)

Konwertuje reprezentację ciągu liczby w określonym stylu i formacie specyficznym dla kultury na równoważnik liczby zmiennoprzecinkowych o podwójnej precyzji.

Uwagi

W programie .NET Core 3.0 lub nowszym wartości, które są zbyt duże do reprezentowania, są zaokrąglane do PositiveInfinity lub NegativeInfinity zgodnie ze specyfikacją IEEE 754. W poprzednich wersjach, w tym .NET Framework, analizowanie wartości, która była zbyt duża, aby reprezentować, spowodowała awarię.

Parse(String)

Źródło:
Double.cs
Źródło:
Double.cs
Źródło:
Double.cs
Źródło:
Double.cs
Źródło:
Double.cs

Konwertuje reprezentację ciągu liczby na równoważną liczbę zmiennoprzecinkową o podwójnej precyzji.

public:
 static double Parse(System::String ^ s);
public static double Parse(string s);
static member Parse : string -> double
Public Shared Function Parse (s As String) As Double

Parametry

s
String

Ciąg zawierający liczbę do przekonwertowania.

Zwraca

Liczba zmiennoprzecinkowa o podwójnej precyzji, która jest równoważna wartości liczbowej lub symbolowi określonemu w elemencie s.

Wyjątki

Parametr s ma wartość null.

s nie reprezentuje liczby w prawidłowym formacie.

Tylko programy .NET Framework i .NET Core 2.2 i starsze: s reprezentują liczbę mniejszą niż Double.MinValue lub większą niż Double.MaxValue.

Przykłady

Poniższy przykład ilustruje użycie Parse(String) metody .

public class Temperature {
    // Parses the temperature from a string in form
    // [ws][sign]digits['F|'C][ws]
    public static Temperature Parse(string s) {
        Temperature temp = new Temperature();

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

        return temp;
    }

    // The value holder
    protected double m_value;

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

    public double Celsius {
        get {
            return (m_value-32.0)/1.8;
        }
        set {
            m_value = 1.8*value+32.0;
        }
    }
}
type Temperature() =
    // Parses the temperature from a string in form
    // [ws][sign]digits['F|'C][ws]
    static member Parse(s: string) =
        let temp = Temperature()

        if s.TrimEnd(null).EndsWith "'F" then
            temp.Value <- Double.Parse(s.Remove(s.LastIndexOf '\'', 2) )
        elif s.TrimEnd(null).EndsWith "'C" then
            temp.Celsius <- Double.Parse(s.Remove(s.LastIndexOf '\'', 2) )
        else
            temp.Value <- Double.Parse s
        temp

    member val Value = 0. with get, set

    member this.Celsius
        with get () =
            (this.Value - 32.) / 1.8
        and set (value) =
            this.Value <- 1.8 * value + 32.
Public Class Temperature
    ' Parses the temperature from a string in form
    ' [ws][sign]digits['F|'C][ws]
    Public Shared Function Parse(ByVal s As String) As Temperature
        Dim temp As New Temperature()

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

    ' The value holder
    Protected m_value As Double

    Public Property Value() As Double
        Get
            Return m_value
        End Get
        Set(ByVal Value As Double)
            m_value = Value
        End Set
    End Property

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

Uwagi

W programie .NET Core 3.0 lub nowszym wartości, które są zbyt duże do reprezentowania, są zaokrąglane do PositiveInfinity lub NegativeInfinity zgodnie ze specyfikacją IEEE 754. W poprzednich wersjach, w tym .NET Framework, analizowanie wartości, która była zbyt duża, aby reprezentować, spowodowała awarię.

Parametr s może zawierać symbol , NumberFormatInfo.NegativeInfinitySymbollub NumberFormatInfo.NaNSymbol bieżącej kulturyNumberFormatInfo.PositiveInfinitySymbol. To porównanie ciągów jest bez uwzględniania wielkości liter w programie .NET Core 3.0 i nowszych wersjach, ale uwzględnia wielkość liter w poprzednich wersjach, w tym .NET Framework. Parametr s może być również ciągiem formularza:

[ws][podpis][cyfry całkowite[,]]cyfry całkowite[.[cyfry ułamkowe]][E[znak]cyfry wykładnicze][ws]

Elementy w nawiasach kwadratowych ([ i ]) są opcjonalne. W poniższej tabeli opisano każdy element.

Pierwiastek Opis
Ws Seria znaków odstępów.
podpis Symbol znaku ujemnego (-) lub symbol znaku dodatniego (+). Można użyć tylko znaku wiodącego.
cyfry całkowite Seria cyfr z zakresu od 0 do 9, która określa integralną część liczby. Przebiegi cyfr całkowitych można podzielić na partycje za pomocą symbolu separatora grup. Na przykład w niektórych kulturach przecinek (,) oddziela grupy tysięcy. Element całkowitocyfrowy może być nieobecny , jeśli ciąg zawiera element ułamkowych cyfr .
, Symbol separatora tysięcy specyficzny dla kultury.
. Symbol separatora dziesiętnego specyficznego dla kultury.
cyfry ułamkowe Seria cyfr od 0 do 9 określająca część ułamkową liczby.
E Znak "e" lub "E", który wskazuje, że wartość jest reprezentowana w notacji wykładniczej (naukowej).
cyfry wykładnicze Seria cyfr z zakresu od 0 do 9, która określa wykładnik.

Parametr s jest interpretowany przy użyciu kombinacji NumberStyles.Float flag i NumberStyles.AllowThousands . Oznacza to, że białe znaki i tysiące separatorów są dozwolone, na przykład, podczas gdy symbole waluty nie są. Aby uzyskać bardziej precyzyjną kontrolę nad tym, które elementy stylu są dozwolone, s aby operacja analizy powiodła się, wywołaj metodę Double.Parse(String, NumberStyles)Double.Parse(String, NumberStyles, IFormatProvider) lub .

Parametr s jest interpretowany przy użyciu informacji o formatowaniu w obiekcie zainicjowanym NumberFormatInfo dla bieżącej kultury. Aby uzyskać więcej informacji, zobacz CurrentInfo. Aby przeanalizować ciąg przy użyciu informacji o formatowaniu innej kultury, wywołaj metodę Double.Parse(String, IFormatProvider) or Double.Parse(String, NumberStyles, IFormatProvider) .

Zazwyczaj, jeśli przekażesz Double.Parse metodę ciąg utworzony przez wywołanie Double.ToString metody, zwracana jest oryginalna Double wartość. Jednak w programach .NET Framework i .NET Core 2.2 i starszych wersjach wartości mogą nie być równe z powodu utraty precyzji. Ponadto próba przeanalizowania reprezentacji Double.MinValue ciągu lub Double.MaxValue nie powiedzie się w obie strony. W programach .NET Framework i .NET Core 2.2 i poprzednich wersjach zgłaszany jest błąd OverflowException. Poniższy przykład zawiera ilustrację.

   string value;

   value = Double.MinValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException) {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }

   value = Double.MaxValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException) {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }

   // Format without the default precision.
   value = Double.MinValue.ToString("G17");
   try
   {
       Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException)
   {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }
// 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.
//    -1.79769313486232E+308
open System

[<EntryPoint>]
let main _ =
    let value = string Double.MinValue
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    let value = string Double.MaxValue
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    // Format without the default precision.
    let value = Double.MinValue.ToString "G17"
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    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.
//    -1.79769313486232E+308
Dim value As String

value = Double.MinValue.ToString()
Try
   Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try

value = Double.MaxValue.ToString()
Try
   Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try

' Format without the default precision.
value = Double.MinValue.ToString("G17")
Try 
    Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try
' The example displays the following output:
'    -1.79769313486232E+308 is outside the range of the Double type.
'    1.79769313486232E+308 is outside the range of the Double type.            
'    -1.79769313486232E+308

W programach .NET Framework i .NET Core 2.2 i starszych wersjach, jeśli s nie ma zakresu Double typu danych, Parse(String) metoda zgłasza błąd OverflowException.

W przypadku platformy .NET Core 3.0 i nowszych wersji żaden wyjątek nie jest zgłaszany, gdy s nie ma zakresu Double typu danych. W większości przypadków metoda zwróci Double.PositiveInfinity wartość lub Double.NegativeInfinity. Istnieje jednak niewielki zestaw wartości, które są uważane za zbliżone do maksymalnej lub minimalnej wartości Double niż do dodatniej lub ujemnej nieskończoności. W takich przypadkach metoda zwraca Double.MaxValue wartość lub Double.MinValue.

Jeśli separator napotkany w parametrze s podczas operacji analizy, a odpowiednia waluta lub separatory liczbowe i separatory grup są takie same, operacja analizy zakłada, że separator jest separatorem dziesiętnym, a nie separatorem grupy. Aby uzyskać więcej informacji na temat separatorów, zobacz CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparatori NumberGroupSeparator.

Zobacz też

Dotyczy

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Źródło:
Double.cs
Źródło:
Double.cs
Źródło:
Double.cs
Źródło:
Double.cs

Analizuje zakres znaków UTF-8 w wartość.

public:
 static double Parse(ReadOnlySpan<System::Byte> utf8Text, IFormatProvider ^ provider) = IUtf8SpanParsable<double>::Parse;
public static double Parse(ReadOnlySpan<byte> utf8Text, IFormatProvider? provider);
static member Parse : ReadOnlySpan<byte> * IFormatProvider -> double
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), provider As IFormatProvider) As Double

Parametry

utf8Text
ReadOnlySpan<Byte>

Zakres znaków UTF-8 do przeanalizowania.

provider
IFormatProvider

Obiekt, który udostępnia informacje o formatowaniu specyficznym dla kultury.utf8Text

Zwraca

Wynik analizowania utf8Text.

Implementuje

Dotyczy

Parse(ReadOnlySpan<Char>, IFormatProvider)

Źródło:
Double.cs
Źródło:
Double.cs
Źródło:
Double.cs
Źródło:
Double.cs
Źródło:
Double.cs

Analizuje zakres znaków w wartości.

public:
 static double Parse(ReadOnlySpan<char> s, IFormatProvider ^ provider) = ISpanParsable<double>::Parse;
public static double Parse(ReadOnlySpan<char> s, IFormatProvider? provider);
static member Parse : ReadOnlySpan<char> * IFormatProvider -> double
Public Shared Function Parse (s As ReadOnlySpan(Of Char), provider As IFormatProvider) As Double

Parametry

s
ReadOnlySpan<Char>

Zakres znaków do przeanalizowania.

provider
IFormatProvider

Obiekt, który udostępnia informacje o formatowaniu specyficznym dla kultury.s

Zwraca

Wynik analizowania s.

Implementuje

Dotyczy

Parse(String, NumberStyles)

Źródło:
Double.cs
Źródło:
Double.cs
Źródło:
Double.cs
Źródło:
Double.cs
Źródło:
Double.cs

Konwertuje reprezentację ciągu liczby w określonym stylu na równoważnik liczby zmiennoprzecinkowych o podwójnej precyzji.

public:
 static double Parse(System::String ^ s, System::Globalization::NumberStyles style);
public static double Parse(string s, System.Globalization.NumberStyles style);
static member Parse : string * System.Globalization.NumberStyles -> double
Public Shared Function Parse (s As String, style As NumberStyles) As Double

Parametry

s
String

Ciąg zawierający liczbę do przekonwertowania.

style
NumberStyles

Bitowa kombinacja wartości wyliczenia wskazująca elementy stylu, które mogą być obecne w elemecie s. Typowa wartość do określenia jest kombinacją w połączeniu Float z elementem AllowThousands.

Zwraca

Liczba zmiennoprzecinkowa o podwójnej precyzji, która jest równoważna wartości liczbowej lub symbolowi określonemu w elemencie s.

Wyjątki

Parametr s ma wartość null.

s nie reprezentuje liczby w prawidłowym formacie.

Tylko programy .NET Framework i .NET Core 2.2 i starsze: s reprezentują liczbę mniejszą niż Double.MinValue lub większą niż Double.MaxValue.

style nie jest wartością NumberStyles .

-lub-

style AllowHexSpecifier zawiera wartość .

Przykłady

W poniższym przykładzie użyto Parse(String, NumberStyles) metody , aby przeanalizować reprezentacje ciągów Double wartości przy użyciu kultury en-US.

public static void Main()
{
   // Set current thread culture to en-US.
   Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");

   string value;
   NumberStyles styles;

   // Parse a string in exponential notation with only the AllowExponent flag.
   value = "-1.063E-02";
   styles = NumberStyles.AllowExponent;
   ShowNumericValue(value, styles);

   // Parse a string in exponential notation
   // with the AllowExponent and Number flags.
   styles = NumberStyles.AllowExponent | NumberStyles.Number;
   ShowNumericValue(value, styles);

   // Parse a currency value with leading and trailing white space, and
   // white space after the U.S. currency symbol.
   value = " $ 6,164.3299  ";
   styles = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
   ShowNumericValue(value, styles);

   // Parse negative value with thousands separator and decimal.
   value = "(4,320.64)";
   styles = NumberStyles.AllowParentheses | NumberStyles.AllowTrailingSign |
            NumberStyles.Float;
   ShowNumericValue(value, styles);

   styles = NumberStyles.AllowParentheses | NumberStyles.AllowTrailingSign |
            NumberStyles.Float | NumberStyles.AllowThousands;
   ShowNumericValue(value, styles);
}

private static void ShowNumericValue(string value, NumberStyles styles)
{
   double number;
   try
   {
      number = Double.Parse(value, styles);
      Console.WriteLine("Converted '{0}' using {1} to {2}.",
                        value, styles.ToString(), number);
   }
   catch (FormatException)
   {
      Console.WriteLine("Unable to parse '{0}' with styles {1}.",
                        value, styles.ToString());
   }
   Console.WriteLine();
}
// The example displays the following output to the console:
//    Unable to parse '-1.063E-02' with styles AllowExponent.
//
//    Converted '-1.063E-02' using AllowTrailingSign, AllowThousands, Float to -0.01063.
//
//    Converted ' $ 6,164.3299  ' using Number, AllowCurrencySymbol to 6164.3299.
//
//    Unable to parse '(4,320.64)' with styles AllowTrailingSign, AllowParentheses, Float.
//
//    Converted '(4,320.64)' using AllowTrailingSign, AllowParentheses, AllowThousands, Float to -4320.64.
open System
open System.Globalization
open System.Threading

let showNumericValue (value: string) (styles: NumberStyles) =
    try
        let number = Double.Parse(value, styles)
        printfn $"Converted '{value}' using {styles} to {number}."
    with :? FormatException ->
        printfn $"Unable to parse '{value}' with styles {styles}."
    printfn ""

[<EntryPoint>]
let main _ =
    // Set current thread culture to en-US.
    Thread.CurrentThread.CurrentCulture <- CultureInfo.CreateSpecificCulture "en-US"

    // Parse a string in exponential notation with only the AllowExponent flag.
    let value = "-1.063E-02"
    let styles = NumberStyles.AllowExponent
    showNumericValue value styles

    // Parse a string in exponential notation
    // with the AllowExponent and Number flags.
    let styles = NumberStyles.AllowExponent ||| NumberStyles.Number
    showNumericValue value styles

    // Parse a currency value with leading and trailing white space, and
    // white space after the U.S. currency symbol.
    let value = " $ 6,164.3299  "
    let styles = NumberStyles.Number ||| NumberStyles.AllowCurrencySymbol
    showNumericValue value styles

    // Parse negative value with thousands separator and decimal.
    let value = "(4,320.64)"
    let styles = 
        NumberStyles.AllowParentheses ||| NumberStyles.AllowTrailingSign ||| NumberStyles.Float
    showNumericValue value styles

    let styles = 
        NumberStyles.AllowParentheses ||| NumberStyles.AllowTrailingSign ||| NumberStyles.Float ||| NumberStyles.AllowThousands
    showNumericValue value styles

    0

// The example displays the following output to the console:
//    Unable to parse '-1.063E-02' with styles AllowExponent.
//
//    Converted '-1.063E-02' using AllowTrailingSign, AllowThousands, Float to -0.01063.
//
//    Converted ' $ 6,164.3299  ' using Number, AllowCurrencySymbol to 6164.3299.
//
//    Unable to parse '(4,320.64)' with styles AllowTrailingSign, AllowParentheses, Float.
//
//    Converted '(4,320.64)' using AllowTrailingSign, AllowParentheses, AllowThousands, Float to -4320.64.
Public Sub Main()
   ' Set current thread culture to en-US.
   Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US")
         
   Dim value As String
   Dim styles As NumberStyles
   
   ' Parse a string in exponential notation with only the AllowExponent flag. 
   value = "-1.063E-02"
   styles = NumberStyles.AllowExponent
   ShowNumericValue(value, styles) 
   
   ' Parse a string in exponential notation
   ' with the AllowExponent and Number flags.
   styles = NumberStyles.AllowExponent Or NumberStyles.Number
   ShowNumericValue(value, styles)

   ' Parse a currency value with leading and trailing white space, and
   ' white space after the U.S. currency symbol.
   value = " $ 6,164.3299  "
   styles = NumberStyles.Number Or NumberStyles.AllowCurrencySymbol
   ShowNumericValue(value, styles)
   
   ' Parse negative value with thousands separator and decimal.
   value = "(4,320.64)"
   styles = NumberStyles.AllowParentheses Or NumberStyles.AllowTrailingSign _
            Or NumberStyles.Float 
   ShowNumericValue(value, styles)
   
   styles = NumberStyles.AllowParentheses Or NumberStyles.AllowTrailingSign _
            Or NumberStyles.Float Or NumberStyles.AllowThousands
   ShowNumericValue(value, styles)
End Sub

Private Sub ShowNumericValue(value As String, styles As NumberStyles)
   Dim number As Double
   Try
      number = Double.Parse(value, styles)
      Console.WriteLine("Converted '{0}' using {1} to {2}.", _
                        value, styles.ToString(), number)
   Catch e As FormatException
      Console.WriteLine("Unable to parse '{0}' with styles {1}.", _
                        value, styles.ToString())
   End Try
   Console.WriteLine()                           
End Sub
' The example displays the following output to the console:
'    Unable to parse '-1.063E-02' with styles AllowExponent.
'    
'    Converted '-1.063E-02' using AllowTrailingSign, AllowThousands, Float to -0.01063.
'    
'    Converted ' $ 6,164.3299  ' using Number, AllowCurrencySymbol to 6164.3299.
'    
'    Unable to parse '(4,320.64)' with styles AllowTrailingSign, AllowParentheses, Float.
'    
'    Converted '(4,320.64)' using AllowTrailingSign, AllowParentheses, AllowThousands, Float to -4320.64.

Uwagi

W programie .NET Core 3.0 lub nowszym wartości, które są zbyt duże do reprezentowania, są zaokrąglane do PositiveInfinity lub NegativeInfinity zgodnie ze specyfikacją IEEE 754. W poprzednich wersjach, w tym .NET Framework, analizowanie wartości, która była zbyt duża, aby reprezentować, spowodowała awarię.

Parametr style definiuje elementy stylu (takie jak białe znaki, separatory tysięcy i symbole waluty), które są dozwolone w parametrze s dla operacji analizowania, która zakończy się powodzeniem. Musi to być kombinacja flag bitowych z NumberStyles wyliczenia. Następujące NumberStyles elementy członkowskie nie są obsługiwane:

Parametr s może zawierać symbol , NumberFormatInfo.NegativeInfinitySymbollub NumberFormatInfo.NaNSymbol bieżącej kulturyNumberFormatInfo.PositiveInfinitySymbol. To porównanie ciągów jest bez uwzględniania wielkości liter w programie .NET Core 3.0 i nowszych wersjach, ale uwzględnia wielkość liter w poprzednich wersjach, w tym .NET Framework. W zależności od wartości styleparametru s parametr może również mieć postać:

[ws][$][znak][cyfry całkowite[,]]cyfry całkowite[.[cyfry ułamkowe]][E[znak]cyfry wykładnicze][ws]

Elementy w nawiasach kwadratowych ([ i ]) są opcjonalne. W poniższej tabeli opisano każdy element.

Pierwiastek Opis
Ws Seria znaków odstępów. Białe znaki mogą pojawić się na początku s , jeśli style zawiera flagę NumberStyles.AllowLeadingWhite , i może pojawić się na końcu s , jeśli style zawiera flagę NumberStyles.AllowTrailingWhite .
$ Symbol waluty specyficznej dla kultury. Jego pozycja w ciągu jest definiowana przez NumberFormatInfo.CurrencyNegativePattern właściwości i NumberFormatInfo.CurrencyPositivePattern bieżącej kultury. Symbol waluty bieżącej kultury może pojawić się, s jeśli style zawiera flagę NumberStyles.AllowCurrencySymbol .
podpis Symbol znaku ujemnego (-) lub symbol znaku dodatniego (+). Znak może pojawić się na początku s , jeśli style zawiera flagę NumberStyles.AllowLeadingSign i może pojawić się na końcu s , jeśli style zawiera flagę NumberStyles.AllowTrailingSign . Nawiasy mogą służyć do wskazywania wartości ujemnej, s jeśli style zawiera flagę NumberStyles.AllowParentheses .
cyfry całkowite Seria cyfr z zakresu od 0 do 9, która określa integralną część liczby. Element całkowitocyfrowy może być nieobecny , jeśli ciąg zawiera element ułamkowych cyfr .
, Separator grup specyficzny dla kultury. Symbol separatora grup bieżącej kultury może pojawić się, s jeśli style zawiera flagę NumberStyles.AllowThousands
. Symbol separatora dziesiętnego specyficznego dla kultury. Symbol dziesiętny bieżącej kultury może pojawić się, s jeśli style zawiera flagę NumberStyles.AllowDecimalPoint .
cyfry ułamkowe Seria cyfr od 0 do 9 określająca część ułamkową liczby. Cyfry ułamkowe mogą być wyświetlane, s jeśli style zawiera flagę NumberStyles.AllowDecimalPoint .
E Znak "e" lub "E", który wskazuje, że wartość jest reprezentowana w notacji wykładniczej (naukowej). Parametr s może reprezentować liczbę w notacji wykładniczej, jeśli style zawiera flagę NumberStyles.AllowExponent .
cyfry wykładnicze Seria cyfr z zakresu od 0 do 9, która określa wykładnik.

Nuta

Wszystkie znaki NUL (U+0000) w obiekcie s są ignorowane przez operację analizowania, niezależnie od wartości argumentu style .

Ciąg z cyframi (który odpowiada NumberStyles.None stylowi) zawsze analizuje się pomyślnie, jeśli znajduje się w zakresie Double typu. Pozostałe System.Globalization.NumberStyles elementy członkowskie kontrolują, które mogą być obecne, ale nie muszą być obecne, w ciągu wejściowym. W poniższej tabeli przedstawiono, jak poszczególne NumberStyles flagi wpływają na elementy, które mogą być obecne w programie s.

Wartość NumberStyles Elementy dozwolone s oprócz cyfr
None Tylko element cyfr całkowitych .
AllowDecimalPoint Elementy separatora dziesiętnego (.) i cyfr ułamkowych .
AllowExponent Znak "e" lub "E", który wskazuje notację wykładniczą. Ta flaga sama obsługuje wartości w cyfrachE formularza; dodatkowe flagi są potrzebne do pomyślnego analizowania ciągów z takimi elementami jak znaki dodatnie lub ujemne i symbole punktów dziesiętnych.
AllowLeadingWhite Element ws na początku elementu s.
AllowTrailingWhite Element ws na końcu elementu s.
AllowLeadingSign Element sign na początku elementu s.
AllowTrailingSign Element sign na końcu elementu s.
AllowParentheses Element znaku w postaci nawiasów ujętą w wartość liczbową.
AllowThousands Element separatora tysięcy (,).
AllowCurrencySymbol Element currency ($).
Currency Wszystkie elementy. s Nie można jednak reprezentować liczby szesnastkowej ani liczby w notacji wykładniczej.
Float Element ws na początku lub na końcu sznaku na początku znaku na początku sznaku i symbolu przecinka dziesiętnego (.). Parametr s może również używać notacji wykładniczej.
Number ws signElementy separatora , , tysięcy (,) i separatora dziesiętnego (.).
Any Wszystkie elementy. s Nie można jednak reprezentować liczby szesnastkowej.

Parametr s jest analizowany przy użyciu informacji o formatowaniu w obiekcie zainicjowanym NumberFormatInfo dla bieżącej kultury systemu. Aby uzyskać więcej informacji, zobacz CurrentInfo.

Zazwyczaj, jeśli przekażesz Double.Parse metodę ciąg utworzony przez wywołanie Double.ToString metody, zwracana jest oryginalna Double wartość. Jednak ze względu na utratę dokładności wartości mogą nie być równe. Ponadto próba przeanalizowania reprezentacji Double.MinValue ciągu lub Double.MaxValue nie powiedzie się w obie strony. W programach .NET Framework i .NET Core 2.2 i poprzednich wersjach zgłaszany jest błąd OverflowException. W przypadku platformy .NET Core 3.0 lub nowszych wersji zostanie ona zwrócona Double.NegativeInfinity , jeśli próbujesz przeanalizować MinValue lub Double.PositiveInfinity jeśli próbujesz przeanalizować MaxValue. Poniższy przykład zawiera ilustrację.

   string value;

   value = Double.MinValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException) {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }

   value = Double.MaxValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException) {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }

   // Format without the default precision.
   value = Double.MinValue.ToString("G17");
   try
   {
       Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException)
   {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }
// 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.
//    -1.79769313486232E+308
open System

[<EntryPoint>]
let main _ =
    let value = string Double.MinValue
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    let value = string Double.MaxValue
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    // Format without the default precision.
    let value = Double.MinValue.ToString "G17"
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    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.
//    -1.79769313486232E+308
Dim value As String

value = Double.MinValue.ToString()
Try
   Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try

value = Double.MaxValue.ToString()
Try
   Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try

' Format without the default precision.
value = Double.MinValue.ToString("G17")
Try 
    Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try
' The example displays the following output:
'    -1.79769313486232E+308 is outside the range of the Double type.
'    1.79769313486232E+308 is outside the range of the Double type.            
'    -1.79769313486232E+308

W programach .NET Framework i .NET Core 2.2 i starszych wersjach, jeśli s nie ma zakresu Double typu danych, Parse(String, NumberStyles) metoda zgłasza błąd OverflowException.

W przypadku platformy .NET Core 3.0 i nowszych wersji żaden wyjątek nie jest zgłaszany, gdy s nie ma zakresu Double typu danych. W większości przypadków Parse(String, NumberStyles) metoda zwróci Double.PositiveInfinity wartość lub Double.NegativeInfinity. Istnieje jednak niewielki zestaw wartości, które są uważane za zbliżone do maksymalnej lub minimalnej wartości Double niż do dodatniej lub ujemnej nieskończoności. W takich przypadkach metoda zwraca Double.MaxValue wartość lub Double.MinValue.

Jeśli separator napotkany w parametrze s podczas operacji analizy, a odpowiednia waluta lub separatory liczbowe i separatory grup są takie same, operacja analizy zakłada, że separator jest separatorem dziesiętnym, a nie separatorem grupy. Aby uzyskać więcej informacji na temat separatorów, zobacz CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparatori NumberGroupSeparator.

Zobacz też

Dotyczy

Parse(String, IFormatProvider)

Źródło:
Double.cs
Źródło:
Double.cs
Źródło:
Double.cs
Źródło:
Double.cs
Źródło:
Double.cs

Konwertuje reprezentację ciągu liczby w określonym formacie specyficznym dla kultury na równoważnik liczby zmiennoprzecinkowych o podwójnej precyzji.

public:
 static double Parse(System::String ^ s, IFormatProvider ^ provider);
public:
 static double Parse(System::String ^ s, IFormatProvider ^ provider) = IParsable<double>::Parse;
public static double Parse(string s, IFormatProvider provider);
public static double Parse(string s, IFormatProvider? provider);
static member Parse : string * IFormatProvider -> double
Public Shared Function Parse (s As String, provider As IFormatProvider) As Double

Parametry

s
String

Ciąg zawierający liczbę do przekonwertowania.

provider
IFormatProvider

Obiekt, który dostarcza informacje o formatowaniu specyficznym dla kultury.s

Zwraca

Liczba zmiennoprzecinkowa o podwójnej precyzji, która jest równoważna wartości liczbowej lub symbolowi określonemu w elemencie s.

Implementuje

Wyjątki

Parametr s ma wartość null.

s nie reprezentuje liczby w prawidłowym formacie.

Tylko programy .NET Framework i .NET Core 2.2 i starsze: s reprezentują liczbę mniejszą niż Double.MinValue lub większą niż Double.MaxValue.

Przykłady

Poniższy przykład to procedura obsługi zdarzeń kliknięcia przycisku formularza internetowego. Używa tablicy zwracanej przez HttpRequest.UserLanguages właściwość w celu określenia ustawień regionalnych użytkownika. Następnie tworzy wystąpienie CultureInfo obiektu, który odpowiada tym ustawień regionalnych. Obiekt NumberFormatInfo , który należy do tego CultureInfo obiektu, jest następnie przekazywany do Parse(String, IFormatProvider) metody w celu przekonwertowania danych wejściowych użytkownika na Double wartość.

protected void OkToDouble_Click(object sender, EventArgs e)
{
    string locale;
    double number;
    CultureInfo culture;

    // Return if string is empty
    if (String.IsNullOrEmpty(this.inputNumber.Text))
        return;

    // Get locale of web request to determine possible format of number
    if (Request.UserLanguages.Length == 0)
        return;
    locale = Request.UserLanguages[0];
    if (String.IsNullOrEmpty(locale))
        return;

    // Instantiate CultureInfo object for the user's locale
    culture = new CultureInfo(locale);

    // Convert user input from a string to a number
    try
    {
        number = Double.Parse(this.inputNumber.Text, culture.NumberFormat);
    }
    catch (FormatException)
    {
        return;
    }
    catch (OverflowException)
    {
        return;
    }
    // Output number to label on web form
    this.outputNumber.Text = "Number is " + number.ToString();
}
Protected Sub OkToDouble_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles OkToDouble.Click
    Dim locale As String
    Dim culture As CultureInfo
    Dim number As Double

    ' Return if string is empty
    If String.IsNullOrEmpty(Me.inputNumber.Text) Then Exit Sub

    ' Get locale of web request to determine possible format of number
    If Request.UserLanguages.Length = 0 Then Exit Sub
    locale = Request.UserLanguages(0)
    If String.IsNullOrEmpty(locale) Then Exit Sub

    ' Instantiate CultureInfo object for the user's locale
    culture = New CultureInfo(locale)

    ' Convert user input from a string to a number
    Try
        number = Double.Parse(Me.inputNumber.Text, culture.NumberFormat)
    Catch ex As FormatException
        Exit Sub
    Catch ex As Exception
        Exit Sub
    End Try

    ' Output number to label on web form
    Me.outputNumber.Text = "Number is " & number.ToString()
End Sub

Uwagi

W programie .NET Core 3.0 lub nowszym wartości, które są zbyt duże do reprezentowania, są zaokrąglane do PositiveInfinity lub NegativeInfinity zgodnie ze specyfikacją IEEE 754. W poprzednich wersjach, w tym .NET Framework, analizowanie wartości, która była zbyt duża, aby reprezentować, spowodowała awarię.

To przeciążenie Parse(String, IFormatProvider) metody jest zwykle używane do konwertowania tekstu, który można sformatować na różne sposoby na Double wartość. Na przykład może służyć do konwertowania tekstu wprowadzonego przez użytkownika na pole tekstowe HTML na wartość liczbową.

Parametr s jest interpretowany przy użyciu kombinacji NumberStyles.Float flag i NumberStyles.AllowThousands . Parametr s może zawierać NumberFormatInfo.PositiveInfinitySymbolsymbol , NumberFormatInfo.NegativeInfinitySymbollub NumberFormatInfo.NaNSymbol dla kultury określonej przez provider. To porównanie ciągów jest bez uwzględniania wielkości liter w programie .NET Core 3.0 i nowszych wersjach, ale uwzględnia wielkość liter w poprzednich wersjach, w tym .NET Framework. Parametr s może również zawierać ciąg formularza:

[ws][podpis]cyfry całkowite[.[cyfry ułamkowe]][E[znak]cyfry wykładnicze][ws]

Elementy opcjonalne są oprawione w nawiasy kwadratowe ([ i ]). Elementy zawierające termin "cyfry" składają się z serii znaków liczbowych od 0 do 9.

Pierwiastek Opis
Ws Seria znaków odstępów.
podpis Symbol znaku ujemnego (-) lub symbol znaku dodatniego (+).
cyfry całkowite Seria cyfr z zakresu od 0 do 9, która określa integralną część liczby. Przebiegi cyfr całkowitych można podzielić na partycje za pomocą symbolu separatora grup. Na przykład w niektórych kulturach przecinek (,) oddziela grupy tysięcy. Element całkowitocyfrowy może być nieobecny , jeśli ciąg zawiera element ułamkowych cyfr .
. Symbol separatora dziesiętnego specyficznego dla kultury.
cyfry ułamkowe Seria cyfr od 0 do 9 określająca część ułamkową liczby.
E Znak "e" lub "E", który wskazuje, że wartość jest reprezentowana w notacji wykładniczej (naukowej).
cyfry wykładnicze Seria cyfr z zakresu od 0 do 9, która określa wykładnik.

Aby uzyskać więcej informacji na temat formatów liczbowych, zobacz temat Typy formatowania .

Parametr provider jest implementacją IFormatProvider , której GetFormat metoda zwraca NumberFormatInfo obiekt, który dostarcza informacje specyficzne dla kultury używane w interpretowaniu formatu s. Zazwyczaj jest NumberFormatInfo to obiekt lub CultureInfo . Jeśli provider nie null można uzyskać wartości lub nie NumberFormatInfo można uzyskać, używane są informacje o formatowaniu bieżącej kultury systemu.

Zazwyczaj, jeśli przekażesz Double.Parse metodę ciąg utworzony przez wywołanie Double.ToString metody, zwracana jest oryginalna Double wartość. Jednak ze względu na utratę dokładności wartości mogą nie być równe. Ponadto próba przeanalizowania reprezentacji Double.MinValue ciągu lub Double.MaxValue nie powiedzie się w obie strony. W programach .NET Framework i .NET Core 2.2 i poprzednich wersjach zgłaszany jest błąd OverflowException. W przypadku platformy .NET Core 3.0 lub nowszych wersji zostanie ona zwrócona Double.NegativeInfinity , jeśli próbujesz przeanalizować MinValue lub Double.PositiveInfinity jeśli próbujesz przeanalizować MaxValue. Poniższy przykład zawiera ilustrację.

   string value;

   value = Double.MinValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException) {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }

   value = Double.MaxValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException) {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }

   // Format without the default precision.
   value = Double.MinValue.ToString("G17");
   try
   {
       Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException)
   {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }
// 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.
//    -1.79769313486232E+308
open System

[<EntryPoint>]
let main _ =
    let value = string Double.MinValue
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    let value = string Double.MaxValue
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    // Format without the default precision.
    let value = Double.MinValue.ToString "G17"
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    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.
//    -1.79769313486232E+308
Dim value As String

value = Double.MinValue.ToString()
Try
   Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try

value = Double.MaxValue.ToString()
Try
   Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try

' Format without the default precision.
value = Double.MinValue.ToString("G17")
Try 
    Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try
' The example displays the following output:
'    -1.79769313486232E+308 is outside the range of the Double type.
'    1.79769313486232E+308 is outside the range of the Double type.            
'    -1.79769313486232E+308

W programach .NET Framework i .NET Core 2.2 i starszych wersjach, jeśli s nie ma zakresu Double typu danych, Parse(String, IFormatProvider) metoda zgłasza błąd OverflowException.

W przypadku platformy .NET Core 3.0 i nowszych wersji żaden wyjątek nie jest zgłaszany, gdy s nie ma zakresu Double typu danych. W większości przypadków Parse(String, IFormatProvider) metoda zwróci Double.PositiveInfinity wartość lub Double.NegativeInfinity. Istnieje jednak niewielki zestaw wartości, które są uważane za zbliżone do maksymalnej lub minimalnej wartości Double niż do dodatniej lub ujemnej nieskończoności. W takich przypadkach metoda zwraca Double.MaxValue wartość lub Double.MinValue.

Jeśli separator napotkany w parametrze s podczas operacji analizy, a odpowiednia waluta lub separatory liczbowe i separatory grup są takie same, operacja analizy zakłada, że separator jest separatorem dziesiętnym, a nie separatorem grupy. Aby uzyskać więcej informacji na temat separatorów, zobacz CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparatori NumberGroupSeparator.

Zobacz też

Dotyczy

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

Źródło:
Double.cs
Źródło:
Double.cs
Źródło:
Double.cs
Źródło:
Double.cs

Analizuje zakres znaków UTF-8 w wartość.

public static double Parse(ReadOnlySpan<byte> utf8Text, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.Float, IFormatProvider? provider = default);
static member Parse : ReadOnlySpan<byte> * System.Globalization.NumberStyles * IFormatProvider -> double
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), Optional style As NumberStyles = System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.Float, Optional provider As IFormatProvider = Nothing) As Double

Parametry

utf8Text
ReadOnlySpan<Byte>

Zakres znaków UTF-8 do przeanalizowania.

style
NumberStyles

Bitowa kombinacja stylów liczbowych, które mogą być obecne w pliku utf8Text.

provider
IFormatProvider

Obiekt, który udostępnia informacje o formatowaniu specyficznym dla kultury.utf8Text

Zwraca

Wynik analizowania utf8Text.

Implementuje

Dotyczy

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Źródło:
Double.cs
Źródło:
Double.cs
Źródło:
Double.cs
Źródło:
Double.cs
Źródło:
Double.cs

Konwertuje zakres znaków zawierający ciąg reprezentujący liczbę w określonym stylu i formacie specyficznym dla kultury na równoważnik liczby zmiennoprzecinkowych o podwójnej precyzji.

public static double Parse(ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.Float, IFormatProvider? provider = default);
public static double Parse(ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.Float, IFormatProvider provider = default);
static member Parse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider -> double
Public Shared Function Parse (s As ReadOnlySpan(Of Char), Optional style As NumberStyles = System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.Float, Optional provider As IFormatProvider = Nothing) As Double

Parametry

s
ReadOnlySpan<Char>

Zakres znaków zawierający liczbę do przekonwertowania.

style
NumberStyles

Bitowa kombinacja wartości wyliczenia wskazująca elementy stylu, które mogą być obecne w elemecie s. Typowa wartość do określenia jest Float połączona z elementem AllowThousands.

provider
IFormatProvider

Obiekt, który dostarcza informacje o formatowaniu specyficznym dla kultury.s

Zwraca

Liczba zmiennoprzecinkowa o podwójnej precyzji, która jest równoważna wartości liczbowej lub symbolowi określonemu w elemencie s.

Implementuje

Wyjątki

s nie reprezentuje wartości liczbowej.

style nie jest wartością NumberStyles .

-lub-

style jest wartością AllowHexSpecifier .

Uwagi

W programie .NET Core 3.0 lub nowszym wartości, które są zbyt duże do reprezentowania, są zaokrąglane do PositiveInfinity lub NegativeInfinity zgodnie ze specyfikacją IEEE 754. W poprzednich wersjach, w tym .NET Framework, analizowanie wartości, która była zbyt duża, aby reprezentować, spowodowała awarię.

Jeśli s jest poza zakresem Double typu danych, metoda zwraca Double.NegativeInfinity wartość , jeśli s jest mniejsza niż Double.MinValue i Double.PositiveInfinity jeśli s jest większa niż Double.MaxValue.

Dotyczy

Parse(String, NumberStyles, IFormatProvider)

Źródło:
Double.cs
Źródło:
Double.cs
Źródło:
Double.cs
Źródło:
Double.cs
Źródło:
Double.cs

Konwertuje reprezentację ciągu liczby w określonym stylu i formacie specyficznym dla kultury na równoważnik liczby zmiennoprzecinkowych o podwójnej precyzji.

public:
 static double Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider);
public:
 static double Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider) = System::Numerics::INumberBase<double>::Parse;
public static double Parse(string s, System.Globalization.NumberStyles style, IFormatProvider provider);
public static double Parse(string s, System.Globalization.NumberStyles style, IFormatProvider? provider);
static member Parse : string * System.Globalization.NumberStyles * IFormatProvider -> double
Public Shared Function Parse (s As String, style As NumberStyles, provider As IFormatProvider) As Double

Parametry

s
String

Ciąg zawierający liczbę do przekonwertowania.

style
NumberStyles

Bitowa kombinacja wartości wyliczenia wskazująca elementy stylu, które mogą być obecne w elemecie s. Typowa wartość do określenia jest Float połączona z elementem AllowThousands.

provider
IFormatProvider

Obiekt, który dostarcza informacje o formatowaniu specyficznym dla kultury.s

Zwraca

Liczba zmiennoprzecinkowa o podwójnej precyzji, która jest równoważna wartości liczbowej lub symbolowi określonemu w elemencie s.

Implementuje

Wyjątki

Parametr s ma wartość null.

s nie reprezentuje wartości liczbowej.

style nie jest wartością NumberStyles .

-lub-

style jest wartością AllowHexSpecifier .

Tylko programy .NET Framework i .NET Core 2.2 i starsze: s reprezentują liczbę mniejszą niż Double.MinValue lub większą niż Double.MaxValue.

Przykłady

Poniższy przykład ilustruje użycie Parse(String, NumberStyles, IFormatProvider) metody w celu przypisania kilku reprezentacji ciągu wartości temperatury do Temperature obiektu.

using System;
using System.Globalization;

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

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

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

   protected double m_value;

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

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

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

public class TestTemperature
{
   public static void Main()
   {
      string value;
      NumberStyles styles;
      IFormatProvider provider;
      Temperature temp;

      value = "25,3'C";
      styles = NumberStyles.Float;
      provider = CultureInfo.CreateSpecificCulture("fr-FR");
      temp = Temperature.Parse(value, styles, provider);
      Console.WriteLine("{0} degrees Fahrenheit equals {1} degrees Celsius.",
                        temp.Fahrenheit, temp.Celsius);

      value = " (40) 'C";
      styles = NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite
               | NumberStyles.AllowParentheses;
      provider = NumberFormatInfo.InvariantInfo;
      temp = Temperature.Parse(value, styles, provider);
      Console.WriteLine("{0} degrees Fahrenheit equals {1} degrees Celsius.",
                        temp.Fahrenheit, temp.Celsius);

      value = "5,778E03'C";      // Approximate surface temperature of the Sun
      styles = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands |
               NumberStyles.AllowExponent;
      provider = CultureInfo.CreateSpecificCulture("en-GB");
      temp = Temperature.Parse(value, styles, provider);
      Console.WriteLine("{0} degrees Fahrenheit equals {1} degrees Celsius.",
                        temp.Fahrenheit.ToString("N"), temp.Celsius.ToString("N"));
   }
}
open System
open System.Globalization

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

    let mutable m_value = 0.

    member _.Value
        with get () = m_value
        and private set (value) = m_value <- value

    member _.Celsius
        with get() = (m_value - 32.) / 1.8
        and private set (value) = m_value <- value * 1.8 + 32.

    member _.Fahrenheit =
        m_value

    // Parses the temperature from a string. Temperature scale is
    // indicated by 'F (for Fahrenheit) or 'C (for Celsius) at the end
    // of the string.
    static member Parse(s: string, styles: NumberStyles, provider: IFormatProvider) =
        let temp = new Temperature()

        if s.TrimEnd(null).EndsWith "'F" then
            temp.Value <- Double.Parse(s.Remove(s.LastIndexOf(char 39), 2), styles, provider)
        else
            if s.TrimEnd(null).EndsWith "'C" then
                temp.Celsius <- Double.Parse(s.Remove(s.LastIndexOf(char 39), 2), styles, provider)
            else
                temp.Value <- Double.Parse(s, styles, provider)
        temp

[<EntryPoint>]
let main _ =
    let value = "25,3'C"
    let styles = NumberStyles.Float
    let provider = CultureInfo.CreateSpecificCulture "fr-FR"
    let temp = Temperature.Parse(value, styles, provider)
    printfn $"{temp.Fahrenheit} degrees Fahrenheit equals {temp.Celsius} degrees Celsius."

    let value = " (40) 'C"
    let styles = NumberStyles.AllowLeadingWhite ||| NumberStyles.AllowTrailingWhite ||| NumberStyles.AllowParentheses
    let provider = NumberFormatInfo.InvariantInfo
    let temp = Temperature.Parse(value, styles, provider)
    printfn $"{temp.Fahrenheit} degrees Fahrenheit equals {temp.Celsius} degrees Celsius."

    let value = "5,778E03'C"      // Approximate surface temperature of the Sun
    let styles = NumberStyles.AllowDecimalPoint ||| NumberStyles.AllowThousands ||| NumberStyles.AllowExponent
    let provider = CultureInfo.CreateSpecificCulture "en-GB"
    let temp = Temperature.Parse(value, styles, provider)
    printfn $"{temp.Fahrenheit:N} degrees Fahrenheit equals {temp.Celsius:N} degrees Celsius."

    0
Imports System.Globalization

Public Class Temperature
   ' Parses the temperature from a string. Temperature scale is 
   ' indicated by 'F (for Fahrenheit) or 'C (for Celsius) at the end
   ' of the string.
   Public Shared Function Parse(s As String, styles As NumberStyles, _
                                provider As IFormatProvider) As Temperature
      Dim temp As New Temperature()
      
      If s.TrimEnd(Nothing).EndsWith("'F") Then
         temp.Value = Double.Parse(s.Remove(s.LastIndexOf("'"c), 2), _
                                   styles, provider)
      Else
         If s.TrimEnd(Nothing).EndsWith("'C") Then
            temp.Celsius = Double.Parse(s.Remove(s.LastIndexOf("'"c), 2), _
                                        styles, provider)
         Else
            temp.Value = Double.Parse(s, styles, provider)         
         End If
      End If
      Return temp      
   End Function 
   
   ' Declare private constructor so Temperature so only Parse method can
   ' create a new instance
   Private Sub New 
   End Sub

   Protected m_value As Double
   
   Public Property Value() As Double
      Get
         Return m_value
      End Get
      
      Private Set
         m_value = Value
      End Set
   End Property
   
   Public Property Celsius() As Double
      Get
         Return (m_value - 32) / 1.8
      End Get
      Private Set
         m_value = Value * 1.8 + 32
      End Set
   End Property
   
   Public ReadOnly Property Fahrenheit() As Double
      Get
         Return m_Value
      End Get   
   End Property   
End Class

Public Module TestTemperature
   Public Sub Main
      Dim value As String
      Dim styles As NumberStyles
      Dim provider As IFormatProvider
      Dim temp As Temperature
      
      value = "25,3'C"
      styles = NumberStyles.Float
      provider = CultureInfo.CreateSpecificCulture("fr-FR")
      temp = Temperature.Parse(value, styles, provider)
      Console.WriteLine("{0} degrees Fahrenheit equals {1} degrees Celsius.", _
                        temp.Fahrenheit, temp.Celsius)
      
      value = " (40) 'C"
      styles = NumberStyles.AllowLeadingWhite Or NumberStyles.AllowTrailingWhite _
               Or NumberStyles.AllowParentheses
      provider = NumberFormatInfo.InvariantInfo
      temp = Temperature.Parse(value, styles, provider)
      Console.WriteLine("{0} degrees Fahrenheit equals {1} degrees Celsius.", _
                        temp.Fahrenheit, temp.Celsius)
      
      value = "5,778E03'C"      ' Approximate surface temperature of the Sun
      styles = NumberStyles.AllowDecimalPoint Or NumberStyles.AllowThousands Or _
               NumberStyles.AllowExponent
      provider = CultureInfo.CreateSpecificCulture("en-GB") 
      temp = Temperature.Parse(value, styles, provider)
      Console.WriteLine("{0} degrees Fahrenheit equals {1} degrees Celsius.", _
                        temp.Fahrenheit.ToString("N"), temp.Celsius.ToString("N"))
                                
   End Sub
End Module

Uwagi

W programie .NET Core 3.0 lub nowszym wartości, które są zbyt duże do reprezentowania, są zaokrąglane do PositiveInfinity lub NegativeInfinity zgodnie ze specyfikacją IEEE 754. W poprzednich wersjach, w tym .NET Framework, analizowanie wartości, która była zbyt duża, aby reprezentować, spowodowała awarię.

Parametr style definiuje elementy stylu (takie jak białe znaki, separatory tysięcy i symbole waluty), które są dozwolone w parametrze s dla operacji analizowania, która zakończy się powodzeniem. Musi to być kombinacja flag bitowych z NumberStyles wyliczenia. Następujące NumberStyles elementy członkowskie nie są obsługiwane:

Parametr s może zawierać NumberFormatInfo.PositiveInfinitySymbolsymbol , NumberFormatInfo.NegativeInfinitySymbollub NumberFormatInfo.NaNSymbol dla kultury określonej przez provider. To porównanie ciągów jest bez uwzględniania wielkości liter w programie .NET Core 3.0 i nowszych wersjach, ale uwzględnia wielkość liter w poprzednich wersjach, w tym .NET Framework. W zależności od wartości styleparametru s parametr może również mieć postać:

[ws] [$] [znak][cyfry całkowite,]cyfry całkowite[.[ cyfry ułamkowe]][E[znak]cyfry wykładnicze][ws]

Elementy w nawiasach kwadratowych ([ i ]) są opcjonalne. W poniższej tabeli opisano każdy element.

Pierwiastek Opis
Ws Seria znaków odstępów. Białe znaki mogą pojawić się na początku s , jeśli style zawiera flagę NumberStyles.AllowLeadingWhite , i może pojawić się na końcu s , jeśli style zawiera flagę NumberStyles.AllowTrailingWhite .
$ Symbol waluty specyficznej dla kultury. Jego pozycja w ciągu jest definiowana przez NumberFormatInfo.CurrencyNegativePattern właściwości i NumberFormatInfo.CurrencyPositivePattern bieżącej kultury. Symbol waluty bieżącej kultury może pojawić się, s jeśli style zawiera flagę NumberStyles.AllowCurrencySymbol .
podpis Symbol znaku ujemnego (-) lub symbol znaku dodatniego (+). Znak może pojawić się na początku s , jeśli style zawiera flagę NumberStyles.AllowLeadingSign i może pojawić się na końcu s , jeśli style zawiera flagę NumberStyles.AllowTrailingSign . Nawiasy mogą służyć do wskazywania wartości ujemnej, s jeśli style zawiera flagę NumberStyles.AllowParentheses .
cyfry całkowite Seria cyfr z zakresu od 0 do 9, która określa integralną część liczby. Element całkowitocyfrowy może być nieobecny , jeśli ciąg zawiera element ułamkowych cyfr .
, Separator grup specyficzny dla kultury. Symbol separatora grup bieżącej kultury może pojawić się, s jeśli style zawiera flagę NumberStyles.AllowThousands
. Symbol separatora dziesiętnego specyficznego dla kultury. Symbol dziesiętny bieżącej kultury może pojawić się, s jeśli style zawiera flagę NumberStyles.AllowDecimalPoint .
cyfry ułamkowe Seria cyfr od 0 do 9 określająca część ułamkową liczby. Cyfry ułamkowe mogą być wyświetlane, s jeśli style zawiera flagę NumberStyles.AllowDecimalPoint .
E Znak "e" lub "E", który wskazuje, że wartość jest reprezentowana w notacji wykładniczej (naukowej). Parametr s może reprezentować liczbę w notacji wykładniczej, jeśli style zawiera flagę NumberStyles.AllowExponent .
cyfry wykładnicze Seria cyfr z zakresu od 0 do 9, która określa wykładnik.

Nuta

Wszystkie znaki NUL (U+0000) w obiekcie s są ignorowane przez operację analizowania, niezależnie od wartości argumentu style .

Ciąg z cyframi (który odpowiada NumberStyles.None stylowi) zawsze analizuje się pomyślnie, jeśli znajduje się w zakresie Double typu. Pozostałe System.Globalization.NumberStyles elementy członkowskie kontrolują, które mogą być obecne, ale nie muszą być obecne, w ciągu wejściowym. W poniższej tabeli przedstawiono, jak poszczególne NumberStyles flagi wpływają na elementy, które mogą być obecne w programie s.

Wartość NumberStyles Elementy dozwolone s oprócz cyfr
None Tylko element cyfr całkowitych .
AllowDecimalPoint Elementy separatora dziesiętnego (.) i cyfr ułamkowych .
AllowExponent Znak "e" lub "E", który wskazuje notację wykładniczą. Ta flaga sama obsługuje wartości w cyfrachE formularza; dodatkowe flagi są potrzebne do pomyślnego analizowania ciągów z takimi elementami jak znaki dodatnie lub ujemne i symbole punktów dziesiętnych.
AllowLeadingWhite Element ws na początku elementu s.
AllowTrailingWhite Element ws na końcu elementu s.
AllowLeadingSign Element sign na początku elementu s.
AllowTrailingSign Element sign na końcu elementu s.
AllowParentheses Element znaku w postaci nawiasów ujętą w wartość liczbową.
AllowThousands Element separatora tysięcy (,).
AllowCurrencySymbol Element currency ($).
Currency Wszystkie elementy. s Nie można jednak reprezentować liczby szesnastkowej ani liczby w notacji wykładniczej.
Float Element ws na początku lub na końcu sznaku na początku znaku na początku sznaku i symbolu przecinka dziesiętnego (.). Parametr s może również używać notacji wykładniczej.
Number ws signElementy separatora , , tysięcy (,) i separatora dziesiętnego (.).
Any Wszystkie elementy. s Nie można jednak reprezentować liczby szesnastkowej.

Parametr provider jest implementacją IFormatProvider , której GetFormat metoda zwraca NumberFormatInfo obiekt, który dostarcza informacje specyficzne dla kultury używane w interpretowaniu formatu s. Zazwyczaj jest NumberFormatInfo to obiekt lub CultureInfo . Jeśli provider nie null można uzyskać wartości lub nie NumberFormatInfo można uzyskać, używane są informacje o formatowaniu bieżącej kultury systemu.

Zazwyczaj, jeśli przekażesz Double.Parse metodę ciąg utworzony przez wywołanie Double.ToString metody, zwracana jest oryginalna Double wartość. Jednak ze względu na utratę dokładności wartości mogą nie być równe. Ponadto próba przeanalizowania reprezentacji MinValue ciągu lub Double.MaxValue nie powiedzie się w obie strony. W programach .NET Framework i .NET Core 2.2 i poprzednich wersjach zgłaszany jest błąd OverflowException. W przypadku platformy .NET Core 3.0 lub nowszych wersji zostanie ona zwrócona Double.NegativeInfinity , jeśli próbujesz przeanalizować MinValue lub Double.PositiveInfinity jeśli próbujesz przeanalizować MaxValue. Poniższy przykład zawiera ilustrację.

   string value;

   value = Double.MinValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException) {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }

   value = Double.MaxValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException) {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }

   // Format without the default precision.
   value = Double.MinValue.ToString("G17");
   try
   {
       Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException)
   {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }
// 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.
//    -1.79769313486232E+308
open System

[<EntryPoint>]
let main _ =
    let value = string Double.MinValue
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    let value = string Double.MaxValue
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    // Format without the default precision.
    let value = Double.MinValue.ToString "G17"
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    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.
//    -1.79769313486232E+308
Dim value As String

value = Double.MinValue.ToString()
Try
   Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try

value = Double.MaxValue.ToString()
Try
   Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try

' Format without the default precision.
value = Double.MinValue.ToString("G17")
Try 
    Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try
' The example displays the following output:
'    -1.79769313486232E+308 is outside the range of the Double type.
'    1.79769313486232E+308 is outside the range of the Double type.            
'    -1.79769313486232E+308

W programach .NET Framework i .NET Core 2.2 i starszych wersjach, jeśli s nie ma zakresu Double typu danych, Parse(String, NumberStyles, IFormatProvider) metoda zgłasza błąd OverflowException.

W przypadku platformy .NET Core 3.0 i nowszych wersji żaden wyjątek nie jest zgłaszany, gdy s nie ma zakresu Double typu danych. W większości przypadków Parse(String, NumberStyles, IFormatProvider) metoda zwróci Double.PositiveInfinity wartość lub Double.NegativeInfinity. Istnieje jednak niewielki zestaw wartości, które są uważane za zbliżone do maksymalnej lub minimalnej wartości Double niż do dodatniej lub ujemnej nieskończoności. W takich przypadkach metoda zwraca Double.MaxValue wartość lub Double.MinValue.

Jeśli separator napotkany w parametrze s podczas operacji analizy, a odpowiednia waluta lub separatory liczbowe i separatory grup są takie same, operacja analizy zakłada, że separator jest separatorem dziesiętnym, a nie separatorem grupy. Aby uzyskać więcej informacji na temat separatorów, zobacz CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparatori NumberGroupSeparator.

Zobacz też

Dotyczy