Double.Parse Metodo

Definizione

Converte la rappresentazione di stringa di un numero nel rispettivo numero a virgola mobile a precisione doppia equivalente.

Overload

Parse(String, NumberStyles, IFormatProvider)

Converte la rappresentazione di stringa di un numero in uno stile specificato e in un formato specifico delle impostazioni cultura nel numero a virgola mobile e precisione doppia equivalente.

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Converte un intervallo di caratteri che contiene la rappresentazione stringa di un numero in uno stile specificato e in un formato specifico delle impostazioni cultura nel numero a virgola mobile a precisione doppia equivalente.

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

Analizza un intervallo di caratteri UTF-8 in un valore.

Parse(String, IFormatProvider)

Converte la rappresentazione di stringa di un numero in un determinato formato specifico delle impostazioni cultura nel numero a virgola mobile e doppia precisione equivalente.

Parse(String)

Converte la rappresentazione di stringa di un numero nel rispettivo numero a virgola mobile a precisione doppia equivalente.

Parse(ReadOnlySpan<Char>, IFormatProvider)

Analizza un intervallo di caratteri in un valore.

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Analizza un intervallo di caratteri UTF-8 in un valore.

Parse(String, NumberStyles)

Converte la rappresentazione di stringa di un numero in uno stile specificato nel rispettivo numero a virgola mobile a precisione doppia equivalente.

Commenti

In .NET Core 3.0 e versioni successive, i valori troppo grandi da rappresentare vengono arrotondati a PositiveInfinity o NegativeInfinity come richiesto dalla specifica IEEE 754. Nelle versioni precedenti, tra cui .NET Framework, analizzare un valore troppo grande per rappresentare un errore.

Parse(String, NumberStyles, IFormatProvider)

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

Converte la rappresentazione di stringa di un numero in uno stile specificato e in un formato specifico delle impostazioni cultura nel numero a virgola mobile e precisione doppia equivalente.

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

Parametri

s
String

Stringa contenente un numero da convertire.

style
NumberStyles

Combinazione bit per bit dei valori di enumerazione che indica gli elementi di stile che possono essere presenti in s. Un valore tipico da specificare è Float combinato con AllowThousands.

provider
IFormatProvider

Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura relativamente a s.

Restituisce

Numero a virgola mobile a precisione doppia equivalente al valore numerico o al simbolo specificato in s.

Implementazioni

Eccezioni

s non rappresenta un valore numerico.

style non è un valore di NumberStyles.

-oppure-

style è il valore di AllowHexSpecifier.

Solo .NET Framework e .NET Core 2.2 e versioni precedenti: s rappresenta un numero minore di Double.MinValue o maggiore di Double.MaxValue.

Esempio

Nell'esempio seguente viene illustrato l'uso del Parse(String, NumberStyles, IFormatProvider) metodo per assegnare diverse rappresentazioni di stringa dei valori di temperatura a un Temperature oggetto .

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

Commenti

In .NET Core 3.0 e versioni successive i valori troppo grandi da rappresentare vengono arrotondati a o NegativeInfinity in base alle PositiveInfinity esigenze della specifica IEEE 754. Nelle versioni precedenti, incluso .NET Framework, l'analisi di un valore troppo grande per rappresentare ha generato un errore.

Il style parametro definisce gli elementi di stile, ad esempio spazi vuoti, migliaia di separatori e simboli di valuta, consentiti nel s parametro per l'esito positivo dell'operazione di analisi. Deve essere una combinazione di flag di bit dell'enumerazione NumberStyles . I membri seguenti NumberStyles non sono supportati:

Il s parametro può contenere NumberFormatInfo.PositiveInfinitySymbol, NumberFormatInfo.NegativeInfinitySymbolo NumberFormatInfo.NaNSymbol per le impostazioni cultura specificate da provider. A seconda del valore di style, può anche assumere il formato :

[ws] [$] [sign][integral-digits,]integral-digits[.[ frazionarie]] [E[segno]cifre esponenziali] [ws]

Gli elementi racchiusi tra parentesi quadre ([ e ]) sono facoltativi. La tabella seguente descrive i singoli elementi.

Elemento Descrizione
ws Serie di spazi vuoti. Gli spazi vuoti possono essere visualizzati all'inizio di s se include il NumberStyles.AllowLeadingWhite flag e possono essere visualizzati alla fine di s se style include il NumberStyles.AllowTrailingWhite flag .style
$ Simbolo di valuta specifico delle impostazioni cultura. La posizione nella stringa è definita dalle NumberFormatInfo.CurrencyNegativePattern proprietà e NumberFormatInfo.CurrencyPositivePattern delle impostazioni cultura correnti. Il simbolo di valuta delle impostazioni cultura correnti può essere visualizzato in s se style include il NumberStyles.AllowCurrencySymbol flag .
sign Simbolo di segno negativo (-) o simbolo di segno positivo (+). Il segno può essere visualizzato all'inizio di s se include il NumberStyles.AllowLeadingSign flag e può essere visualizzato alla fine di s se style include il NumberStyles.AllowTrailingSignstyle flag . Le parentesi possono essere usate in s per indicare un valore negativo se style include il NumberStyles.AllowParentheses flag .
cifre integrali Serie di cifre comprese tra 0 e 9 che specificano la parte integrante del numero. L'elemento integral-digits può essere assente se la stringa contiene l'elemento frazionaria.
, Separatore di gruppi specifico delle impostazioni cultura. Il simbolo separatore di gruppo delle impostazioni cultura corrente può essere visualizzato in s se style include il NumberStyles.AllowThousands flag
. Simbolo di virgola decimale specifica delle impostazioni cultura. Il simbolo decimale delle impostazioni cultura corrente può essere visualizzato in s se style include il NumberStyles.AllowDecimalPoint flag .
cifre frazionarie Serie di cifre comprese tra 0 e 9 che specificano la parte frazionaria del numero. Le cifre frazionarie possono essere visualizzate in s se style include il NumberStyles.AllowDecimalPoint flag .
E Carattere "e" o "E", che indica che il valore è rappresentato nella notazione esponenziale (scientifica). Il s parametro può rappresentare un numero in notazione esponenziale se style include il NumberStyles.AllowExponent flag .
cifre esponenziali Serie di cifre comprese tra 0 e 9 che specificano un esponente.

Nota

Qualsiasi carattere NUL di terminazione (U+0000) in s viene ignorato dall'operazione di analisi, indipendentemente dal valore dell'argomento style .

Una stringa con solo cifre (che corrisponde allo NumberStyles.None stile) analizza sempre correttamente se si trova nell'intervallo del Double tipo. Gli elementi di controllo membri rimanenti System.Globalization.NumberStyles che possono essere presenti, ma non devono essere presenti, nella stringa di input. La tabella seguente indica in che modo i singoli NumberStyles flag influiscono sugli elementi che possono essere presenti in s.

Valore NumberStyles Elementi consentiti oltre s alle cifre
None Solo elemento a cifre integrali .
AllowDecimalPoint Elementi decimali (.) e frazionari .
AllowExponent Carattere "e" o "E", che indica la notazione esponenziale. Questo flag supporta da solo i valori nelle cifredel modulo cifre E; sono necessari flag aggiuntivi per analizzare correttamente le stringhe con elementi quali segni positivi o negativi e simboli di virgola decimale.
AllowLeadingWhite Elemento ws all'inizio di s.
AllowTrailingWhite Elemento ws alla fine di s.
AllowLeadingSign Elemento di segno all'inizio di s.
AllowTrailingSign Elemento di segno alla fine di s.
AllowParentheses Elemento di segno sotto forma di parentesi che racchiude il valore numerico.
AllowThousands Elemento separatore delle migliaia (,).
AllowCurrencySymbol Elemento currency ($).
Currency Tutti gli elementi. Tuttavia, s non può rappresentare un numero esadecimale o un numero in notazione esponenziale.
Float Elemento ws all'inizio o alla fine di s, segno all'inizio di se simbolo decimale (.). Il s parametro può anche usare la notazione esponenziale.
Number Elementi wsseparatore , sign, migliaia (,) e separatore decimale (.).
Any Tutti gli elementi. Tuttavia, s non può rappresentare un numero esadecimale.

Il provider parametro è un'implementazione IFormatProvider il cui GetFormat metodo restituisce un NumberFormatInfo oggetto che fornisce informazioni specifiche delle impostazioni cultura utilizzate per interpretare il formato di s. In genere, si tratta di un NumberFormatInfo oggetto o CultureInfo . Se provider è o non è null possibile ottenere un oggetto NumberFormatInfo , vengono utilizzate le informazioni di formattazione per le impostazioni cultura di sistema correnti.

In genere, se si passa al Double.Parse metodo una stringa creata chiamando il Double.ToString metodo , viene restituito il valore originale Double . Tuttavia, a causa di una perdita di precisione, i valori potrebbero non essere uguali. Inoltre, il tentativo di analizzare la rappresentazione di stringa di o MinValueDouble.MaxValue non riesce a eseguire il round trip. In .NET Framework e .NET Core 2.2 e versioni precedenti genera un'eccezione OverflowException. In .NET Core 3.0 e versioni successive, restituisce Double.NegativeInfinityMinValue se si tenta di analizzare o Double.PositiveInfinity se si tenta di analizzare MaxValue. Nell'esempio seguente viene illustrato questo concetto.

   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

In .NET Framework e .NET Core 2.2 e versioni precedenti, se s non è compreso nell'intervallo Double del tipo di dati, il Parse(String, NumberStyles, IFormatProvider) metodo genera un'eccezione OverflowException.

In .NET Core 3.0 e versioni successive non viene generata alcuna eccezione quando s non è compreso nell'intervallo Double di dati. Nella maggior parte dei casi, il Parse(String, NumberStyles, IFormatProvider) metodo restituirà Double.PositiveInfinity o Double.NegativeInfinity. Tuttavia, esiste un piccolo set di valori che vengono considerati più vicini ai valori massimi o minimi di Double rispetto all'infinito positivo o negativo. In questi casi, il metodo restituisce Double.MaxValue o Double.MinValue.

Se viene rilevato un separatore nel s parametro durante un'operazione di analisi e i separatori decimali o numerici e di gruppo applicabili sono gli stessi, l'operazione di analisi presuppone che il separatore sia un separatore decimale anziché un separatore di gruppo. Per altre informazioni sui separatori, vedere CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparatore NumberGroupSeparator.

Vedi anche

Si applica a

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

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

Converte un intervallo di caratteri che contiene la rappresentazione stringa di un numero in uno stile specificato e in un formato specifico delle impostazioni cultura nel numero a virgola mobile a precisione doppia equivalente.

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

Parametri

s
ReadOnlySpan<Char>

Intervallo di caratteri che contiene il numero da convertire.

style
NumberStyles

Combinazione bit per bit dei valori di enumerazione che indica gli elementi di stile che possono essere presenti in s. Un valore tipico da specificare è Float combinato con AllowThousands.

provider
IFormatProvider

Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura relativamente a s.

Restituisce

Numero a virgola mobile a precisione doppia equivalente al valore numerico o al simbolo specificato in s.

Implementazioni

Eccezioni

s non rappresenta un valore numerico.

style non è un valore di NumberStyles.

-oppure-

style è il valore di AllowHexSpecifier.

Commenti

In .NET Core 3.0 e versioni successive i valori troppo grandi da rappresentare vengono arrotondati a o NegativeInfinity in base alle PositiveInfinity esigenze della specifica IEEE 754. Nelle versioni precedenti, incluso .NET Framework, l'analisi di un valore troppo grande per rappresentare ha generato un errore.

Se s non è compreso nell'intervallo Double del tipo di dati, il metodo restituisce Double.NegativeInfinity se s è minore di Double.MinValue e Double.PositiveInfinity se s è maggiore di Double.MaxValue.

Si applica a

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

Source:
Double.cs
Source:
Double.cs

Analizza un intervallo di caratteri UTF-8 in un valore.

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

Parametri

utf8Text
ReadOnlySpan<Byte>

Intervallo di caratteri UTF-8 da analizzare.

style
NumberStyles

Combinazione bit per bit di stili numerici che possono essere presenti in utf8Text.

provider
IFormatProvider

Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura relative a utf8Text.

Restituisce

Risultato dell'analisi utf8Textdi .

Implementazioni

Si applica a

Parse(String, IFormatProvider)

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

Converte la rappresentazione di stringa di un numero in un determinato formato specifico delle impostazioni cultura nel numero a virgola mobile e doppia precisione equivalente.

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

Parametri

s
String

Stringa contenente un numero da convertire.

provider
IFormatProvider

Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura relativamente a s.

Restituisce

Numero a virgola mobile a precisione doppia equivalente al valore numerico o al simbolo specificato in s.

Implementazioni

Eccezioni

s non rappresenta un numero in formato valido.

Solo .NET Framework e .NET Core 2.2 e versioni precedenti: s rappresenta un numero minore di Double.MinValue o maggiore di Double.MaxValue.

Esempio

L'esempio seguente è il gestore eventi click del pulsante di un modulo Web. Usa la matrice restituita dalla HttpRequest.UserLanguages proprietà per determinare le impostazioni locali dell'utente. Crea quindi un'istanza di un CultureInfo oggetto che corrisponde a tali impostazioni locali. L'oggetto NumberFormatInfo appartenente a tale CultureInfo oggetto viene quindi passato al Parse(String, IFormatProvider) metodo per convertire l'input dell'utente in un Double valore.

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

Commenti

In .NET Core 3.0 e versioni successive i valori troppo grandi da rappresentare vengono arrotondati a o NegativeInfinity in base alle PositiveInfinity esigenze della specifica IEEE 754. Nelle versioni precedenti, incluso .NET Framework, l'analisi di un valore troppo grande per rappresentare ha generato un errore.

Questo overload del Parse(String, IFormatProvider) metodo viene in genere usato per convertire il testo che può essere formattato in diversi modi in un Double valore. Ad esempio, può essere usato per convertire il testo immesso da un utente in una casella di testo HTML in un valore numerico.

Il s parametro viene interpretato usando una combinazione di NumberStyles.Float flag e NumberStyles.AllowThousands . Il s parametro può contenere NumberFormatInfo.PositiveInfinitySymbol, NumberFormatInfo.NegativeInfinitySymbolo NumberFormatInfo.NaNSymbol per le impostazioni cultura specificate da provideroppure può contenere una stringa del formato:

[ws] [sign] cifre integrali[.[cifre frazionarie]] [E[segno]cifre esponenziali] [ws]

Gli elementi facoltativi sono racchiusi tra parentesi quadre ([ e ]). Gli elementi che contengono il termine "cifre" sono costituiti da una serie di caratteri numerici compresi tra 0 e 9.

Elemento Descrizione
ws Serie di spazi vuoti.
sign Simbolo di segno negativo (-) o simbolo di segno positivo (+).
cifre integrali Serie di cifre comprese tra 0 e 9 che specificano la parte integrante del numero. Le esecuzioni di cifre integrali possono essere partizionate da un simbolo separatore di gruppo. In alcune impostazioni cultura, ad esempio, una virgola (,) separa i gruppi di migliaia. L'elemento integral-digits può essere assente se la stringa contiene l'elemento frazionaria.
. Simbolo di virgola decimale specifica delle impostazioni cultura.
cifre frazionarie Serie di cifre comprese tra 0 e 9 che specificano la parte frazionaria del numero.
E Carattere "e" o "E", che indica che il valore è rappresentato nella notazione esponenziale (scientifica).
cifre esponenziali Serie di cifre comprese tra 0 e 9 che specificano un esponente.

Per altre informazioni sui formati numerici, vedere l'argomento Formattazione dei tipi .

Il provider parametro è un'implementazione IFormatProvider il cui GetFormat metodo restituisce un NumberFormatInfo oggetto che fornisce informazioni specifiche delle impostazioni cultura utilizzate per interpretare il formato di s. In genere, si tratta di un NumberFormatInfo oggetto o CultureInfo . Se provider è o non è null possibile ottenere un oggetto NumberFormatInfo , vengono utilizzate le informazioni di formattazione per le impostazioni cultura di sistema correnti.

In genere, se si passa al Double.Parse metodo una stringa creata chiamando il Double.ToString metodo , viene restituito il valore originale Double . Tuttavia, a causa di una perdita di precisione, i valori potrebbero non essere uguali. Inoltre, il tentativo di analizzare la rappresentazione di stringa di o Double.MinValueDouble.MaxValue non riesce a eseguire il round trip. In .NET Framework e .NET Core 2.2 e versioni precedenti genera un'eccezione OverflowException. In .NET Core 3.0 e versioni successive, restituisce Double.NegativeInfinityMinValue se si tenta di analizzare o Double.PositiveInfinity se si tenta di analizzare MaxValue. Nell'esempio seguente viene illustrato questo concetto.

   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

In .NET Framework e .NET Core 2.2 e versioni precedenti, se s non è compreso nell'intervallo Double del tipo di dati, il Parse(String, IFormatProvider) metodo genera un'eccezione OverflowException.

In .NET Core 3.0 e versioni successive non viene generata alcuna eccezione quando s non è compreso nell'intervallo Double di dati. Nella maggior parte dei casi, il Parse(String, IFormatProvider) metodo restituirà Double.PositiveInfinity o Double.NegativeInfinity. Tuttavia, esiste un piccolo set di valori che vengono considerati più vicini ai valori massimi o minimi di Double rispetto all'infinito positivo o negativo. In questi casi, il metodo restituisce Double.MaxValue o Double.MinValue.

Se viene rilevato un separatore nel s parametro durante un'operazione di analisi e i separatori decimali o numerici e di gruppo applicabili sono gli stessi, l'operazione di analisi presuppone che il separatore sia un separatore decimale anziché un separatore di gruppo. Per altre informazioni sui separatori, vedere CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparatore NumberGroupSeparator.

Vedi anche

Si applica a

Parse(String)

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

Converte la rappresentazione di stringa di un numero nel rispettivo numero a virgola mobile a precisione doppia equivalente.

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

Parametri

s
String

Stringa contenente un numero da convertire.

Restituisce

Numero a virgola mobile a precisione doppia equivalente al valore numerico o al simbolo specificato in s.

Eccezioni

s non rappresenta un numero in formato valido.

Solo .NET Framework e .NET Core 2.2 e versioni precedenti: s rappresenta un numero minore di Double.MinValue o maggiore di Double.MaxValue.

Esempio

Nell'esempio riportato di seguito viene illustrato l'utilizzo del metodo Parse(String).

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

Commenti

In .NET Core 3.0 e versioni successive i valori troppo grandi da rappresentare vengono arrotondati a o NegativeInfinity in base alle PositiveInfinity esigenze della specifica IEEE 754. Nelle versioni precedenti, incluso .NET Framework, l'analisi di un valore troppo grande per rappresentare ha generato un errore.

Il s parametro può contenere le impostazioni cultura NumberFormatInfo.PositiveInfinitySymbolcorrenti , NumberFormatInfo.NegativeInfinitySymbol, NumberFormatInfo.NaNSymbolo una stringa del formato:

[ws] [sign] [cifre integrali[,]] cifre integrali[.[cifre frazionarie]] [E[segno]cifre esponenziali] [ws]

Gli elementi tra parentesi quadre ([e]) sono facoltativi. La tabella seguente descrive i singoli elementi.

Elemento Descrizione
ws Serie di spazi vuoti.
sign Simbolo di segno negativo (-) o simbolo di segno positivo (+). È possibile usare solo un segno iniziale.
cifre integrali Serie di cifre comprese tra 0 e 9 che specificano la parte integrante del numero. Le esecuzioni di cifre integrali possono essere partizionate da un simbolo separatore di gruppo. In alcune impostazioni cultura, ad esempio, una virgola (,) separa i gruppi di migliaia. L'elemento integral-digits può essere assente se la stringa contiene l'elemento frazionaria.
, Simbolo separatore delle migliaia specifico delle impostazioni cultura.
. Simbolo di virgola decimale specifica delle impostazioni cultura.
cifre frazionarie Serie di cifre comprese tra 0 e 9 che specificano la parte frazionaria del numero.
E Carattere "e" o "E", che indica che il valore è rappresentato nella notazione esponenziale (scientifica).
cifre esponenziali Serie di cifre comprese tra 0 e 9 che specificano un esponente.

Il s parametro viene interpretato usando una combinazione di NumberStyles.Float flag e NumberStyles.AllowThousands . Ciò significa che sono consentiti spazi vuoti e migliaia di separatori, ad esempio, mentre i simboli di valuta non sono. Per un controllo più fine sugli elementi di stile consentiti per s l'esito positivo dell'operazione di analisi, chiamare il Double.Parse(String, NumberStyles) metodo o Double.Parse(String, NumberStyles, IFormatProvider) .

Il s parametro viene interpretato usando le informazioni di formattazione in un NumberFormatInfo oggetto inizializzato per le impostazioni cultura correnti. Per altre informazioni, vedere CurrentInfo. Per analizzare una stringa usando le informazioni di formattazione di altre impostazioni cultura, chiamare il Double.Parse(String, IFormatProvider) metodo o Double.Parse(String, NumberStyles, IFormatProvider) .

In genere, se si passa al Double.Parse metodo una stringa creata chiamando il Double.ToString metodo , viene restituito il valore originale Double . Tuttavia, in .NET Framework e in .NET Core 2.2 e versioni precedenti, i valori potrebbero non essere uguali a causa di una perdita di precisione. Inoltre, il tentativo di analizzare la rappresentazione di stringa di o Double.MinValueDouble.MaxValue non riesce a eseguire il round trip. In .NET Framework e .NET Core 2.2 e versioni precedenti genera un'eccezione OverflowException. Nell'esempio seguente viene illustrato questo concetto.

   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

In .NET Framework e .NET Core 2.2 e versioni precedenti, se s non è compreso nell'intervallo Double del tipo di dati, il Parse(String) metodo genera un'eccezione OverflowException.

In .NET Core 3.0 e versioni successive non viene generata alcuna eccezione quando s non è compreso nell'intervallo Double di dati. Nella maggior parte dei casi, il metodo restituirà Double.PositiveInfinity o Double.NegativeInfinity. Tuttavia, esiste un piccolo set di valori che vengono considerati più vicini ai valori massimi o minimi di Double rispetto all'infinito positivo o negativo. In questi casi, il metodo restituisce Double.MaxValue o Double.MinValue.

Se viene rilevato un separatore nel s parametro durante un'operazione di analisi e i separatori decimali o numerici e di gruppo applicabili sono gli stessi, l'operazione di analisi presuppone che il separatore sia un separatore decimale anziché un separatore di gruppo. Per altre informazioni sui separatori, vedere CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparatore NumberGroupSeparator.

Vedi anche

Si applica a

Parse(ReadOnlySpan<Char>, IFormatProvider)

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

Analizza un intervallo di caratteri in un valore.

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

Parametri

s
ReadOnlySpan<Char>

Intervallo di caratteri da analizzare.

provider
IFormatProvider

Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura relative a s.

Restituisce

Risultato dell'analisi sdi .

Implementazioni

Si applica a

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Source:
Double.cs
Source:
Double.cs

Analizza un intervallo di caratteri UTF-8 in un valore.

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

Parametri

utf8Text
ReadOnlySpan<Byte>

Intervallo di caratteri UTF-8 da analizzare.

provider
IFormatProvider

Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura relative a utf8Text.

Restituisce

Risultato dell'analisi utf8Textdi .

Implementazioni

Si applica a

Parse(String, NumberStyles)

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

Converte la rappresentazione di stringa di un numero in uno stile specificato nel rispettivo numero a virgola mobile a precisione doppia equivalente.

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

Parametri

s
String

Stringa contenente un numero da convertire.

style
NumberStyles

Combinazione bit per bit dei valori di enumerazione che indica gli elementi di stile che possono essere presenti in s. Un valore tipico da specificare è una combinazione di Float e AllowThousands.

Restituisce

Numero a virgola mobile a precisione doppia equivalente al valore numerico o al simbolo specificato in s.

Eccezioni

s non rappresenta un numero in formato valido.

Solo .NET Framework e .NET Core 2.2 e versioni precedenti: s rappresenta un numero minore di Double.MinValue o maggiore di Double.MaxValue.

style non è un valore di NumberStyles.

-oppure-

style include il valore di AllowHexSpecifier.

Esempio

Nell'esempio seguente viene usato il Parse(String, NumberStyles) metodo per analizzare le rappresentazioni di stringa dei Double valori usando le impostazioni cultura 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.

Commenti

In .NET Core 3.0 e versioni successive i valori troppo grandi da rappresentare vengono arrotondati a o NegativeInfinity in base alle PositiveInfinity esigenze della specifica IEEE 754. Nelle versioni precedenti, incluso .NET Framework, l'analisi di un valore troppo grande per rappresentare ha generato un errore.

Il style parametro definisce gli elementi di stile, ad esempio spazi vuoti, migliaia di separatori e simboli di valuta, consentiti nel s parametro per l'esito positivo dell'operazione di analisi. Deve essere una combinazione di flag di bit dell'enumerazione NumberStyles . I membri seguenti NumberStyles non sono supportati:

Il s parametro può contenere le impostazioni cultura NumberFormatInfo.PositiveInfinitySymbolcorrenti , NumberFormatInfo.NegativeInfinitySymbolo NumberFormatInfo.NaNSymbol. A seconda del valore di style, può anche assumere il formato :

[ws] [$][sign][integral-digits[,]]integral-digits[.[cifre frazionarie]] [E[segno]cifre esponenziali] [ws]

Gli elementi tra parentesi quadre ([e]) sono facoltativi. La tabella seguente descrive i singoli elementi.

Elemento Descrizione
ws Serie di spazi vuoti. Gli spazi vuoti possono essere visualizzati all'inizio di s se include il NumberStyles.AllowLeadingWhite flag e possono essere visualizzati alla fine di s se style include il NumberStyles.AllowTrailingWhite flag .style
$ Simbolo di valuta specifico delle impostazioni cultura. La posizione nella stringa è definita dalle NumberFormatInfo.CurrencyNegativePattern proprietà e NumberFormatInfo.CurrencyPositivePattern delle impostazioni cultura correnti. Il simbolo di valuta delle impostazioni cultura correnti può essere visualizzato in s se style include il NumberStyles.AllowCurrencySymbol flag .
sign Simbolo di segno negativo (-) o simbolo di segno positivo (+). Il segno può essere visualizzato all'inizio di s se include il NumberStyles.AllowLeadingSign flag e può essere visualizzato alla fine di s se style include il NumberStyles.AllowTrailingSignstyle flag . Le parentesi possono essere usate in s per indicare un valore negativo se style include il NumberStyles.AllowParentheses flag .
cifre integrali Serie di cifre comprese tra 0 e 9 che specificano la parte integrante del numero. L'elemento integral-digits può essere assente se la stringa contiene l'elemento frazionaria.
, Separatore di gruppi specifico delle impostazioni cultura. Il simbolo separatore di gruppo delle impostazioni cultura corrente può essere visualizzato in s se style include il NumberStyles.AllowThousands flag
. Simbolo di virgola decimale specifica delle impostazioni cultura. Il simbolo decimale delle impostazioni cultura corrente può essere visualizzato in s se style include il NumberStyles.AllowDecimalPoint flag .
cifre frazionarie Serie di cifre comprese tra 0 e 9 che specificano la parte frazionaria del numero. Le cifre frazionarie possono essere visualizzate in s se style include il NumberStyles.AllowDecimalPoint flag .
E Carattere "e" o "E", che indica che il valore è rappresentato nella notazione esponenziale (scientifica). Il s parametro può rappresentare un numero in notazione esponenziale se style include il NumberStyles.AllowExponent flag .
cifre esponenziali Serie di cifre comprese tra 0 e 9 che specificano un esponente.

Nota

Qualsiasi carattere NUL di terminazione (U+0000) in s viene ignorato dall'operazione di analisi, indipendentemente dal valore dell'argomento style .

Una stringa con solo cifre (che corrisponde allo NumberStyles.None stile) analizza sempre correttamente se si trova nell'intervallo del Double tipo. Gli elementi di controllo membri rimanenti System.Globalization.NumberStyles che possono essere presenti, ma non devono essere presenti, nella stringa di input. La tabella seguente indica in che modo i singoli NumberStyles flag influiscono sugli elementi che possono essere presenti in s.

Valore NumberStyles Elementi consentiti oltre s alle cifre
None Solo elemento a cifre integrali .
AllowDecimalPoint Elementi decimali (.) e cifre frazionarie .
AllowExponent Carattere "e" o "E", che indica la notazione esponenziale. Questo flag supporta i valori nellecifre del modulo E; sono necessari flag aggiuntivi per analizzare correttamente le stringhe con elementi come segni positivi o negativi e simboli decimali.
AllowLeadingWhite Elemento ws all'inizio di s.
AllowTrailingWhite Elemento ws alla fine di s.
AllowLeadingSign Elemento di segno all'inizio di s.
AllowTrailingSign Elemento di segno alla fine di s.
AllowParentheses Elemento di segno sotto forma di parentesi che racchiude il valore numerico.
AllowThousands Elemento separatore migliaia (,).
AllowCurrencySymbol Elemento currency ($).
Currency Tutti gli elementi. Tuttavia, s non può rappresentare un numero esadecimale o un numero in notazione esponenziale.
Float Elemento ws all'inizio o alla fine di , segno all'inizio di sse il simbolo decimale (.). Il s parametro può anche usare la notazione esponenziale.
Number Elementi wsseparatore , signmigliaia (,) e decimale (.).
Any Tutti gli elementi. Tuttavia, s non può rappresentare un numero esadecimale.

Il s parametro viene analizzato usando le informazioni di formattazione in un NumberFormatInfo oggetto inizializzato per le impostazioni cultura di sistema correnti. Per altre informazioni, vedere CurrentInfo.

In genere, se si passa il metodo una stringa creata chiamando il Double.Parse metodo, viene restituito il Double.ToString valore originale Double . Tuttavia, a causa di una perdita di precisione, i valori potrebbero non essere uguali. Inoltre, il tentativo di analizzare la rappresentazione stringa di Double.MinValue o Double.MaxValue non riesce a eseguire il round trip. In .NET Framework e .NET Core 2.2 e versioni precedenti genera un OverflowExceptionoggetto . In .NET Core 3.0 e versioni successive, restituisce Double.NegativeInfinityMinValue se si tenta di analizzare o Double.PositiveInfinity se si tenta di analizzare MaxValue. Nell'esempio seguente viene illustrato questo concetto.

   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

In .NET Framework e .NET Core 2.2 e versioni precedenti, se s non è compreso nell'intervallo Double di dati, il Parse(String, NumberStyles) metodo genera un OverflowExceptionoggetto .

In .NET Core 3.0 e versioni successive non viene generata alcuna eccezione quando s non è compreso nell'intervallo Double di dati. Nella maggior parte dei casi, il Parse(String, NumberStyles) metodo restituirà Double.PositiveInfinity o Double.NegativeInfinity. Tuttavia, esiste un piccolo set di valori che vengono considerati più vicini ai valori massimi o minimi di Double che a infinito positivo o negativo. In questi casi, il metodo restituisce Double.MaxValue o Double.MinValue.

Se viene rilevato un separatore nel s parametro durante un'operazione di analisi e i separatori decimali o numerici applicabili sono uguali, l'operazione di analisi presuppone che il separatore sia un separatore decimale anziché un separatore di gruppo. Per altre informazioni sui separatori, vedere CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparatore NumberGroupSeparator.

Vedi anche

Si applica a