Double.Parse Metoda

Definicja

Konwertuje ciąg reprezentujący liczbę na odpowiadającą mu liczbę zmiennoprzecinkową podwójnej precyzji.

Przeciążenia

Parse(String, NumberStyles, IFormatProvider)

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

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

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

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

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

Parse(String, IFormatProvider)

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

Parse(String)

Konwertuje ciąg reprezentujący liczbę na odpowiadającą mu liczbę zmiennoprzecinkową podwójnej precyzji.

Parse(ReadOnlySpan<Char>, IFormatProvider)

Analizuje zakres znaków w wartości.

Parse(ReadOnlySpan<Byte>, IFormatProvider)

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

Parse(String, NumberStyles)

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

Uwagi

W programie .NET Core 3.0 i nowszych wartości, które są zbyt duże do reprezentowania, są zaokrąglane do PositiveInfinity lub NegativeInfinity zgodnie z wymaganiami specyfikacji IEEE 754. W poprzednich wersjach, w tym .NET Framework, analizowanie wartości, która była zbyt duża, aby reprezentować wynik awarii.

Parse(String, NumberStyles, IFormatProvider)

Ź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żność liczb 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ę, którą należy przekształcić.

style
NumberStyles

Bitowa kombinacja wartości wyliczenia, które wskazują elementy stylu, które mogą być obecne w .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ślonej w elemencie s.

Implementuje

Wyjątki

s nie reprezentuje wartości liczbowej.

style nie jest wartością NumberStyles .

-lub-

style jest wartością AllowHexSpecifier .

.NET Framework i .NET Core 2.2 i starsze wersje: s reprezentuje tylko 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ło niepowodzenie.

Parametr style definiuje elementy stylu (takie jak białe znaki, separatory tysięcy i symbole waluty), które są dozwolone w parametrze s operacji analizowania, aby operacja analizy powiodła się. 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.PositiveInfinitySymbolwartość , NumberFormatInfo.NegativeInfinitySymbollub NumberFormatInfo.NaNSymbol dla kultury określonej przez provider. W zależności od wartości parametru stylemoże ona 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 tabeli poniżej opisano każdy element.

Element Opis
Ws Ciąg znaków spacji. 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 specyficzny 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 .
sign Symbol znaku minus (-) lub 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ć s do wskazywania wartości ujemnej, jeśli style zawiera flagę NumberStyles.AllowParentheses .
cyfry-całkowite Ciąg cyfr od 0 do 9, które określają jej część całkowitą. Element całkowitocyfrowy może być nieobecny , jeśli ciąg zawiera element ułamkowe cyfry .
, Separator grupy specyficzny dla kultury. Symbol separatora grup bieżącej kultury może pojawić się, s jeśli style zawiera flagę NumberStyles.AllowThousands
. Symbol dziesiętny specyficzny dla kultury. Symbol punktu dziesiętnego bieżącej kultury może pojawić się, s jeśli style zawiera flagę NumberStyles.AllowDecimalPoint .
cyfry-ułamkowe Ciąg cyfr od 0 do 9, które określają część ułamkową liczby. Cyfry ułamkowe mogą pojawiać się, s jeśli style zawiera flagę NumberStyles.AllowDecimalPoint .
E Znak „e” lub „E”, który wskazuje, że wartość jest reprezentowana w zapisie wykładniczym (naukowym). Parametr s może reprezentować liczbę w notacji wykładniczej, jeśli style zawiera flagę NumberStyles.AllowExponent .
cyfry-wykładnicze Ciąg cyfr od 0 do 9, które określają wykładnik potęgi.

Uwaga

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

Ciąg z tylko cyframi (odpowiadający 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ść wyliczenia NumberStyles Elementy dozwolone oprócz s cyfr
None Tylko element całkowitocyfrowy .
AllowDecimalPoint Elementy separatora dziesiętnego (.) i cyfr ułamkowych .
AllowExponent Znak „e” lub znak „E”, co oznacza zapis wykładniczy. 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 dodatnie lub ujemne znaki i symbole punktów dziesiętnych.
AllowLeadingWhite Element ws na początku elementu s.
AllowTrailingWhite Element ws na końcu elementu s.
AllowLeadingSign Element znaku na początku elementu s.
AllowTrailingSign Element znaku na końcu elementu s.
AllowParentheses Element znaku w postaci nawiasów otaczających wartość liczbową.
AllowThousands Element separatora tysięcznego (,).
AllowCurrencySymbol Element określający walutę ($).
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 si symbolu przecinka dziesiętnego (.). Parametr s może również używać notacji wykładniczej.
Number wsElementy separatora , signtysię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ć informacji o formatowaniu dla bieżącej kultury systemu.

Zwykle, jeśli przekazujesz Double.Parse metodę ciąg, który jest tworzony przez wywołanie Double.ToString metody , zwracana jest oryginalna Double wartość. Jednak ze względu na utratę precyzji wartości mogą być różne. Ponadto próba przeanalizowana reprezentacji ciągu lub Double.MaxValue nie powiodła się, aby przeanalizować reprezentację MinValue ciągu. W .NET Framework i .NET Core 2.2 i poprzednich wersjach zgłaszany jest błąd OverflowException. W programie .NET Core 3.0 i nowszych wersjach jest zwracana Double.NegativeInfinity w przypadku próby analizy MinValue lub Double.PositiveInfinity próby analizy MaxValue. Poniższy przykład stanowi 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 systemach .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 OverflowExceptionbłąd .

W wersjach .NET Core 3.0 i nowszych nie jest zgłaszany wyjątek, 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 wartości maksymalnych lub minimalnych 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 liczb dziesiętne 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<Char>, NumberStyles, IFormatProvider)

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

Konwertuje zakres znaków, który zawiera reprezentację ciągu liczby w określonym stylu i formacie specyficznym dla kultury na równoważność liczb 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, które wskazują elementy stylu, które mogą być obecne w sobiekcie . 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ślonej 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 i nowszych wartości, które są zbyt duże do reprezentowania, są zaokrąglane do PositiveInfinity lub NegativeInfinity zgodnie z wymaganiami specyfikacji IEEE 754. W poprzednich wersjach, w tym .NET Framework, analizowanie wartości, która była zbyt duża, aby reprezentować wynik awarii.

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

Dotyczy

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

Ź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 obiekcie utf8Text.

provider
IFormatProvider

Obiekt, który udostępnia informacje o formatowaniu specyficznym dla kultury dotyczące utf8Textelementu .

Zwraca

Wynik analizy utf8Text.

Implementuje

Dotyczy

Parse(String, IFormatProvider)

Ź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 odpowiednik liczb 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ę, którą należy przekształcić.

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ślonej w elemencie s.

Implementuje

Wyjątki

s nie reprezentuje liczby w prawidłowym formacie.

.NET Framework i .NET Core 2.2 i starsze wersje: s reprezentuje tylko liczbę, która jest mniejsza niż Double.MinValue lub większa niż Double.MaxValue.

Przykłady

W poniższym przykładzie występuje program obsługi zdarzeń kliknięcia przycisku w formularzu sieci Web. Używa tablicy zwróconej przez HttpRequest.UserLanguages właściwość w celu określenia ustawień regionalnych użytkownika. Następnie tworzy wystąpienie obiektu odpowiadającego CultureInfo tym ustawieniam regionalnym. NumberFormatInfo Obiekt, 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 i nowszych wartości, które są zbyt duże do reprezentowania, są zaokrąglane do PositiveInfinity lub NegativeInfinity zgodnie z wymaganiami specyfikacji IEEE 754. W poprzednich wersjach, w tym .NET Framework, analizowanie wartości, która była zbyt duża, aby reprezentować wynik awarii.

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ść. Można na przykład przekonwertować tekst wprowadzony 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.PositiveInfinitySymbolwartość , NumberFormatInfo.NegativeInfinitySymbollub NumberFormatInfo.NaNSymbol dla kultury określonej przez providerelement lub może zawierać ciąg formularza:

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

Elementy opcjonalne są obramowane nawiasami kwadratowymi ([ i ]). Elementy, które zawierają „cyfry”, składają się z serii cyfr od 0 do 9.

Element Opis
Ws Ciąg znaków spacji.
sign Symbol znaku minus (-) lub znaku dodatniego (+).
cyfry-całkowite Ciąg cyfr od 0 do 9, które określają jej część całkowitą. Przebiegi cyfr całkowitych można podzielić na partycje za pomocą symbolu separatora grup. Na przykład w niektórych kulturach przecinek (,) oddziela grupy wartości tysięcznych. Element całkowitocyfrowy może być nieobecny , jeśli ciąg zawiera element ułamkowej cyfry .
. Symbol dziesiętny specyficzny dla kultury.
cyfry-ułamkowe Ciąg cyfr od 0 do 9, które określają część ułamkową liczby.
E Znak „e” lub „E”, który wskazuje, że wartość jest reprezentowana w zapisie wykładniczym (naukowym).
cyfry-wykładnicze Ciąg cyfr od 0 do 9, które określają wykładnik potęgi.

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

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

Zwykle, jeśli przekazujesz Double.Parse metodę ciąg, który jest tworzony przez wywołanie Double.ToString metody, zwracana jest oryginalna Double wartość. Jednak ze względu na utratę precyzji wartości mogą być różne. Ponadto próba przeanalizowania reprezentacji ciągu albo Double.MinValue nie Double.MaxValue powiedzie się. W .NET Framework i .NET Core 2.2 i poprzednich wersjach zgłasza błąd OverflowException. W programie .NET Core 3.0 i nowszych wersjach zostanie ona zwróconaDouble.NegativeInfinity, jeśli próbujesz przeanalizować lub Double.PositiveInfinity jeśli próbujesz MinValue przeanalizować MaxValue. Poniższy przykład stanowi 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 systemach .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 OverflowExceptionbłąd .

W wersjach .NET Core 3.0 i nowszych nie jest zgłaszany wyjątek, 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 wartości maksymalnych lub minimalnych 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 liczb dziesiętne 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)

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

Konwertuje ciąg reprezentujący liczbę na odpowiadającą mu liczbę zmiennoprzecinkową 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ę, którą należy przekształcić.

Zwraca

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

Wyjątki

s nie reprezentuje liczby w prawidłowym formacie.

.NET Framework i .NET Core 2.2 i starsze wersje: s reprezentuje tylko liczbę, która jest mniejsza niż Double.MinValue lub większa niż Double.MaxValue.

Przykłady

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

public ref class Temperature
{
   // Parses the temperature from a string in form
   // [ws][sign]digits['F|'C][ws]
public:
   static Temperature^ Parse( String^ s )
   {
      Temperature^ temp = gcnew Temperature;
      if ( s->TrimEnd(nullptr)->EndsWith( "'F" ) )
      {
         temp->Value = Double::Parse( s->Remove( s->LastIndexOf( '\'' ), 2 ) );
      }
      else
      if ( s->TrimEnd(nullptr)->EndsWith( "'C" ) )
      {
         temp->Celsius = Double::Parse( s->Remove( s->LastIndexOf( '\'' ), 2 ) );
      }
      else
      {
         temp->Value = Double::Parse( s );
      }

      return temp;
   }

protected:
   // The value holder
   double m_value;

public:
   property double Value 
   {
      double get()
      {
         return m_value;
      }
      void set( double value )
      {
         m_value = value;
      }
   }

   property double Celsius 
   {
      double get()
      {
         return (m_value - 32.0) / 1.8;
      }
      void set( double value )
      {
         m_value = 1.8 * value + 32.0;
      }
   }
};
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 i nowszych wartości, które są zbyt duże do reprezentowania, są zaokrąglane do PositiveInfinity lub NegativeInfinity zgodnie z wymaganiami specyfikacji IEEE 754. W poprzednich wersjach, w tym .NET Framework, analizowanie wartości, która była zbyt duża, aby reprezentować wynik awarii.

Parametr s może zawierać ciąg formularza , NumberFormatInfo.NegativeInfinitySymbol, NumberFormatInfo.NaNSymbollub bieżącej kulturyNumberFormatInfo.PositiveInfinitySymbol:

[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 tabeli poniżej opisano każdy element.

Element Opis
Ws Ciąg znaków spacji.
sign Symbol znaku minus (-) lub znaku dodatniego (+). Można użyć tylko znaku wiodącego.
cyfry-całkowite Ciąg cyfr od 0 do 9, które określają jej część całkowitą. Przebiegi cyfr całkowitych można podzielić na partycje za pomocą symbolu separatora grup. Na przykład w niektórych kulturach przecinek (,) oddziela grupy wartości tysięcznych. Element całkowitocyfrowy może być nieobecny , jeśli ciąg zawiera element ułamkowej cyfry .
, Symbol separatora tysięcy specyficzny dla kultury.
. Symbol dziesiętny specyficzny dla kultury.
cyfry-ułamkowe Ciąg cyfr od 0 do 9, które określają część ułamkową liczby.
E Znak „e” lub „E”, który wskazuje, że wartość jest reprezentowana w zapisie wykładniczym (naukowym).
cyfry-wykładnicze Ciąg cyfr od 0 do 9, które określają wykładnik potęgi.

Parametr s jest interpretowany przy użyciu kombinacji NumberStyles.Float flag i NumberStyles.AllowThousands . Oznacza to, że odstępy i tysiące separatorów są dozwolone, na przykład, podczas gdy symbole waluty nie są. Aby uzyskać bardziej precyzyjną kontrolę nad tym, w których elementach stylu można s uruchomić operację analizy, należy wywołać metodę Double.Parse(String, NumberStyles, IFormatProvider)Double.Parse(String, NumberStyles) lub .

Parametr s jest interpretowany przy użyciu informacji formatowania 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) .

Zwykle, jeśli przekazujesz Double.Parse metodę ciąg, który jest tworzony przez wywołanie Double.ToString metody, zwracana jest oryginalna Double wartość. Jednak w .NET Framework i na platformie .NET Core 2.2 i starszych wersjach wartości mogą nie być równe z powodu utraty dokładności. Ponadto próba przeanalizowania reprezentacji ciągu albo Double.MinValue nie Double.MaxValue powiedzie się. W .NET Framework i .NET Core 2.2 i poprzednich wersjach zgłasza błąd OverflowException. Poniższy przykład stanowi 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 systemach .NET Framework i .NET Core 2.2 i starszych wersjach, jeśli s nie ma zakresu Double typu danych, Parse(String) metoda zgłasza OverflowExceptionbłąd .

W wersjach .NET Core 3.0 i nowszych nie jest zgłaszany wyjątek, 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 wartości maksymalnych lub minimalnych 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 liczb dziesiętne 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<Char>, IFormatProvider)

Ź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 dotyczące selementu .

Zwraca

Wynik analizy s.

Implementuje

Dotyczy

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Ź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 dotyczące utf8Textelementu .

Zwraca

Wynik analizy utf8Text.

Implementuje

Dotyczy

Parse(String, NumberStyles)

Ź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żną liczbę zmiennoprzecinkową 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ę, którą należy przekształcić.

style
NumberStyles

Bitowa kombinacja wartości wyliczenia, które wskazują elementy stylu, które mogą być obecne w sobiekcie . Typową wartością do określenia jest kombinacja kombinacji 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ślonej w elemencie s.

Wyjątki

s nie reprezentuje liczby w prawidłowym formacie.

.NET Framework i .NET Core 2.2 i starsze wersje: s reprezentuje tylko liczbę, która jest mniejsza niż Double.MinValue lub większa niż Double.MaxValue.

style nie jest wartością NumberStyles .

-lub-

styleAllowHexSpecifier zawiera wartość.

Przykłady

W poniższym przykładzie Parse(String, NumberStyles) użyto 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 i nowszych wartości, które są zbyt duże do reprezentowania, są zaokrąglane do PositiveInfinity lub NegativeInfinity zgodnie z wymaganiami specyfikacji IEEE 754. W poprzednich wersjach, w tym .NET Framework, analizowanie wartości, która była zbyt duża, aby reprezentować wynik awarii.

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

Parametr s może zawierać bieżącą kulturę NumberFormatInfo.PositiveInfinitySymbol, NumberFormatInfo.NegativeInfinitySymbollub NumberFormatInfo.NaNSymbol. W zależności od wartości parametru stylemoże on 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 tabeli poniżej opisano każdy element.

Element Opis
Ws Ciąg znaków spacji. Biały odstęp może 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 specyficzny 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 być wyświetlany, s jeśli style zawiera flagę NumberStyles.AllowCurrencySymbol .
sign Symbol znaku minus (-) lub 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 Ciąg cyfr od 0 do 9, które określają jej część całkowitą. Element całkowitocyfrowy może być nieobecny , jeśli ciąg zawiera element ułamkowej cyfry .
, Separator grupy specyficzny dla kultury. Symbol separatora grup bieżącej kultury może pojawić się, s jeśli style zawiera flagę NumberStyles.AllowThousands
. Symbol dziesiętny specyficzny dla kultury. Symbol punktu dziesiętnego bieżącej kultury może pojawić się, s jeśli style zawiera flagę NumberStyles.AllowDecimalPoint .
cyfry-ułamkowe Ciąg cyfr od 0 do 9, które określają 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 zapisie wykładniczym (naukowym). Parametr s może reprezentować liczbę w notacji wykładniczej, jeśli style zawiera flagę NumberStyles.AllowExponent .
cyfry-wykładnicze Ciąg cyfr od 0 do 9, które określają wykładnik potęgi.

Uwaga

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

Ciąg z cyframi (odpowiadający NumberStyles.None stylowi) zawsze analizuje się pomyślnie, jeśli znajduje się on 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. Poniższa tabela wskazuje, jak poszczególne NumberStyles flagi wpływają na elementy, które mogą być obecne w elemecie s.

Wartość wyliczenia NumberStyles Elementy dozwolone s oprócz cyfr
None Tylko element całkowitocyfrowy .
AllowDecimalPoint Elementy punktów dziesiętnych (.) i cyfr ułamkowych .
AllowExponent Znak „e” lub znak „E”, co oznacza zapis wykładniczy. Ta flaga sama obsługuje wartości w cyfrachE formularza; Potrzebne są dodatkowe flagi 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 s.
AllowTrailingWhite Element ws na końcu selementu .
AllowLeadingSign Element znaku na początku selementu .
AllowTrailingSign Element znaku na końcu elementu s.
AllowParentheses Element znaku w postaci nawiasów otaczających wartość liczbową.
AllowThousands Element separatora tysięcznego (,).
AllowCurrencySymbol Element określający walutę ($).
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 s, znak na początku s, i symbol dziesiętny (.). Parametr s może również używać notacji wykładniczej.
Number wssignElementy separatora , tysięcy (,) i punktu 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.

Zwykle, jeśli przekazujesz Double.Parse metodę ciąg, który jest tworzony przez wywołanie Double.ToString metody, zwracana jest oryginalna Double wartość. Jednak ze względu na utratę precyzji wartości mogą być różne. Ponadto próba przeanalizowania reprezentacji ciągu albo Double.MinValue nie Double.MaxValue powiedzie się. W .NET Framework i .NET Core 2.2 i poprzednich wersjach zgłasza błąd OverflowException. W programie .NET Core 3.0 i nowszych wersjach zostanie ona zwróconaDouble.NegativeInfinity, jeśli próbujesz przeanalizować lub Double.PositiveInfinity jeśli próbujesz MinValue przeanalizować MaxValue. Poniższy przykład stanowi 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 systemach .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 OverflowExceptionbłąd .

W wersjach .NET Core 3.0 i nowszych nie jest zgłaszany wyjątek, 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 wartości maksymalnych lub minimalnych 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 liczb dziesiętne 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