Single.TryParse Metodo
Definizione
Converte la rappresentazione di stringa di un numero nel numero a virgola mobile a precisione singola equivalente.Converts the string representation of a number to its single-precision floating-point number equivalent. Un valore restituito indica se la conversione è riuscita o meno.A return value indicates whether the conversion succeeded or failed.
Overload
TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Single) |
Converte la rappresentazione intervallo di un numero in uno stile specificato e in un formato specifico delle impostazioni cultura nel numero a virgola mobile a precisione singola equivalente.Converts the span representation of a number in a specified style and culture-specific format to its single-precision floating-point number equivalent. Un valore restituito indica se la conversione è riuscita o meno.A return value indicates whether the conversion succeeded or failed. |
TryParse(String, Single) |
Converte la rappresentazione di stringa di un numero nel numero a virgola mobile a precisione singola equivalente.Converts the string representation of a number to its single-precision floating-point number equivalent. Un valore restituito indica se la conversione è riuscita o meno.A return value indicates whether the conversion succeeded or failed. |
TryParse(ReadOnlySpan<Char>, Single) |
Converte la rappresentazione stringa di un numero in un intervallo di caratteri nel numero a virgola mobile a precisione singola equivalente.Converts the string representation of a number in a character span to its single-precision floating-point number equivalent. Un valore restituito indica se la conversione è riuscita o meno.A return value indicates whether the conversion succeeded or failed. |
TryParse(String, NumberStyles, IFormatProvider, Single) |
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 a precisione singola equivalente.Converts the string representation of a number in a specified style and culture-specific format to its single-precision floating-point number equivalent. Un valore restituito indica se la conversione è riuscita o meno.A return value indicates whether the conversion succeeded or failed. |
Commenti
In .NET Core 3,0 e versioni successive, i valori troppo grandi per essere rappresentati vengono arrotondati a PositiveInfinity o NegativeInfinity come richiesto dalla specifica IEEE 754.In .NET Core 3.0 and later, values that are too large to represent are rounded to PositiveInfinity or NegativeInfinity as required by the IEEE 754 specification. Nelle versioni precedenti, incluse .NET Framework, l'analisi di un valore troppo grande per rappresentare il risultato è un errore.In prior versions, including .NET Framework, parsing a value that was too large to represent resulted in failure.
TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Single)
Converte la rappresentazione intervallo di un numero in uno stile specificato e in un formato specifico delle impostazioni cultura nel numero a virgola mobile a precisione singola equivalente.Converts the span representation of a number in a specified style and culture-specific format to its single-precision floating-point number equivalent. Un valore restituito indica se la conversione è riuscita o meno.A return value indicates whether the conversion succeeded or failed.
public:
static bool TryParse(ReadOnlySpan<char> s, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] float % result);
public static bool TryParse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style, IFormatProvider? provider, out float result);
public static bool TryParse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style, IFormatProvider provider, out float result);
static member TryParse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider * single -> bool
Public Shared Function TryParse (s As ReadOnlySpan(Of Char), style As NumberStyles, provider As IFormatProvider, ByRef result As Single) As Boolean
Parametri
- s
- ReadOnlySpan<Char>
Intervallo di caratteri di sola lettura che contiene il numero da convertire.A read-only character span that contains the number to convert. Per interpretare l'intervallo viene usato lo stile specificato da style
.The span is interpreted using the style specified by style
- style
- NumberStyles
Combinazione bit per bit di valori di enumerazione che indica il formato consentito di s
.A bitwise combination of enumeration values that indicates the permitted format of s
. Un valore tipico da specificare è Float combinato con AllowThousands.A typical value to specify is Float combined with AllowThousands.
- provider
- IFormatProvider
Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura relativamente a s
.An object that supplies culture-specific formatting information about s
.
- result
- Single
Quando questo metodo viene restituito, contiene il numero a virgola mobile a precisione singola equivalente al valore numerico o al simbolo contenuto in s
, se la conversione ha esito positivo oppure zero se la conversione non riesce.When this method returns, contains the single-precision floating-point number equivalent to the numeric value or symbol contained in s
, if the conversion succeeded, or zero if the conversion failed. La conversione non viene eseguita se il parametro s
è null
o Empty, non presenta un formato conforme a style
, rappresenta un numero minore di MinValue o maggiore di MaxValue o se style
non è una combinazione valida di costanti enumerate dell'oggetto NumberStyles.The conversion fails if the s
parameter is null
or Empty, is not in a format compliant with style
, represents a number less than MinValue or greater than MaxValue, or if style
is not a valid combination of NumberStyles enumerated constants. Questo parametro viene passato non inizializzato. Qualsiasi valore fornito in origine in result
verrà sovrascritto.This parameter is passed uninitialized; any value originally supplied in result
will be overwritten.
Restituisce
true
se s
è stato convertito correttamente; in caso contrario, false
.true
if s
was converted successfully; otherwise, false
.
Commenti
In .NET Core 3,0 e versioni successive, i valori troppo grandi per essere rappresentati vengono arrotondati a PositiveInfinity o NegativeInfinity come richiesto dalla specifica IEEE 754.In .NET Core 3.0 and later, values that are too large to represent are rounded to PositiveInfinity or NegativeInfinity as required by the IEEE 754 specification. Nelle versioni precedenti, incluse .NET Framework, l'analisi di un valore troppo grande per rappresentare il risultato è un errore.In prior versions, including .NET Framework, parsing a value that was too large to represent resulted in failure.
Si applica a
TryParse(String, Single)
Converte la rappresentazione di stringa di un numero nel numero a virgola mobile a precisione singola equivalente.Converts the string representation of a number to its single-precision floating-point number equivalent. Un valore restituito indica se la conversione è riuscita o meno.A return value indicates whether the conversion succeeded or failed.
public:
static bool TryParse(System::String ^ s, [Runtime::InteropServices::Out] float % result);
public static bool TryParse (string s, out float result);
public static bool TryParse (string? s, out float? result);
static member TryParse : string * single -> bool
Public Shared Function TryParse (s As String, ByRef result As Single) As Boolean
Parametri
- s
- String
Stringa che rappresenta un numero da convertire.A string representing a number to convert.
- result
- Single
Quando questo metodo viene restituito, contiene il numero a virgola mobile a precisione singola equivalente al valore numerico o al simbolo contenuto in s
, se la conversione ha esito positivo oppure zero se la conversione non riesce.When this method returns, contains single-precision floating-point number equivalent to the numeric value or symbol contained in s
, if the conversion succeeded, or zero if the conversion failed. La conversione non riesce se il parametro s
è null
o Empty o non è un numero in un formato valido.The conversion fails if the s
parameter is null
or Empty or is not a number in a valid format. Non riesce neanche in .NET Framework e .NET Core 2.2 e versioni precedenti se s
rappresenta un numero minore di MinValue o maggiore di MaxValue.It also fails on .NET Framework and .NET Core 2.2 and earlier versions if s
represents a number less than MinValue or greater than MaxValue. Questo parametro viene passato non inizializzato. Qualsiasi valore fornito in origine in result
verrà sovrascritto.This parameter is passed uninitialized; any value originally supplied in result
will be overwritten.
Restituisce
true
se s
è stato convertito correttamente; in caso contrario, false
.true
if s
was converted successfully; otherwise, false
.
Esempio
Nell'esempio seguente viene usato il TryParse(String, Single) metodo per convertire in valori le rappresentazioni di stringa di valori numerici Single .The following example uses the TryParse(String, Single) method to convert the string representations of numeric values to Single values. Si presuppone che en-US siano le impostazioni cultura correnti.It assumes that en-US is the current culture.
string value;
float number;
// Parse a floating-point value with a thousands separator.
value = "1,643.57";
if (Single.TryParse(value, out number))
Console.WriteLine(number);
else
Console.WriteLine("Unable to parse '{0}'.", value);
// Parse a floating-point value with a currency symbol and a
// thousands separator.
value = "$1,643.57";
if (Single.TryParse(value, out number))
Console.WriteLine(number);
else
Console.WriteLine("Unable to parse '{0}'.", value);
// Parse value in exponential notation.
value = "-1.643e6";
if (Single.TryParse(value, out number))
Console.WriteLine(number);
else
Console.WriteLine("Unable to parse '{0}'.", value);
// Parse a negative integer value.
value = "-168934617882109132";
if (Single.TryParse(value, out number))
Console.WriteLine(number);
else
Console.WriteLine("Unable to parse '{0}'.", value);
// The example displays the following output:
// 1643.57
// Unable to parse '$1,643.57'.
// -164300
// -1.689346E+17
Dim value As String
Dim number As Single
' Parse a floating-point value with a thousands separator.
value = "1,643.57"
If Single.TryParse(value, number) Then
Console.WriteLine(number)
Else
Console.WriteLine("Unable to parse '{0}'.", value)
End If
' Parse a floating-point value with a currency symbol and a
' thousands separator.
value = "$1,643.57"
If Single.TryParse(value, number) Then
Console.WriteLine(number)
Else
Console.WriteLine("Unable to parse '{0}'.", value)
End If
' Parse value in exponential notation.
value = "-1.643e6"
If Single.TryParse(value, number)
Console.WriteLine(number)
Else
Console.WriteLine("Unable to parse '{0}'.", value)
End If
' Parse a negative integer number.
value = "-168934617882109132"
If Single.TryParse(value, number)
Console.WriteLine(number)
Else
Console.WriteLine("Unable to parse '{0}'.", value)
End If
' The example displays the following output:
' 1643.57
' Unable to parse '$1,643.57'.
' -1643000
' -1.689346E+17
Commenti
In .NET Core 3,0 e versioni successive, i valori troppo grandi per essere rappresentati vengono arrotondati a PositiveInfinity o NegativeInfinity come richiesto dalla specifica IEEE 754.In .NET Core 3.0 and later, values that are too large to represent are rounded to PositiveInfinity or NegativeInfinity as required by the IEEE 754 specification. Nelle versioni precedenti, incluse .NET Framework, l'analisi di un valore troppo grande per rappresentare il risultato è un errore.In prior versions, including .NET Framework, parsing a value that was too large to represent resulted in failure.
Questo overload è diverso dal Single.Parse(String) Metodo restituendo un valore booleano che indica se l'operazione di analisi ha avuto esito positivo anziché restituire il valore numerico analizzato.This overload differs from the Single.Parse(String) method by returning a Boolean value that indicates whether the parse operation succeeded instead of returning the parsed numeric value. Elimina la necessità di utilizzare la gestione delle eccezioni per verificare un oggetto FormatException nel caso in cui s
non sia valido e non possa essere analizzato correttamente.It eliminates the need to use exception handling to test for a FormatException in the event that s
is invalid and cannot be successfully parsed.
Il s
parametro può contenere PositiveInfinitySymbol , NegativeInfinitySymbol , NaNSymbol (il confronto tra stringhe fa distinzione tra maiuscole e minuscole) o una stringa nel formato seguente:The s
parameter can contain PositiveInfinitySymbol, NegativeInfinitySymbol, NaNSymbol (the string comparison is case-sensitive), or a string of the form:
WS Sign [integrali-cifre,] cifre integrali [. [ frazionarie-cifre]] [e [segno] esponenziale-cifre] [ws][ws][sign][integral-digits,]integral-digits[.[fractional-digits]][e[sign]exponential-digits][ws]
Gli elementi tra parentesi quadre sono facoltativi.Elements in square brackets are optional. La tabella seguente descrive i singoli elementi.The following table describes each element.
ElementoElement | DescrizioneDescription |
---|---|
wsws | Una serie di spazi vuoti.A series of white-space characters. |
signsign | Segno negativo o simbolo di segno positivo.A negative sign or positive sign symbol. |
cifre integraliintegral-digits | Serie di caratteri numerici compreso tra 0 e 9 che specificano la parte integrale del numero.A series of numeric characters ranging from 0 to 9 that specify the integral part of the number. Le cifre integrali possono essere assenti se sono presenti cifre frazionarie.Integral-digits can be absent if there are fractional-digits. |
,, | Simbolo di separatore di gruppo specifico delle impostazioni cultura.A culture-specific group separator symbol. |
.. | Simbolo di virgola decimale specifico delle impostazioni cultura.A culture-specific decimal point symbol. |
cifre frazionariefractional-digits | Serie di caratteri numerici compreso tra 0 e 9 che specificano la parte frazionaria del numero.A series of numeric characters ranging from 0 to 9 that specify the fractional part of the number. |
EE | Carattere maiuscolo o minuscolo "e" che indica la notazione esponenziale (scientifica).An uppercase or lowercase character 'e', that indicates exponential (scientific) notation. |
cifre esponenzialiexponential-digits | Una serie di caratteri numerici compreso tra 0 e 9 che specificano un esponente.A series of numeric characters ranging from 0 to 9 that specify an exponent. |
Il s
parametro viene interpretato utilizzando una combinazione dei NumberStyles.Float flag e NumberStyles.AllowThousands .The s
parameter is interpreted using a combination of the NumberStyles.Float and NumberStyles.AllowThousands flags. Ciò significa che gli spazi vuoti e i separatori di migliaia sono consentiti, ma i simboli di valuta non lo sono.This means that white space and thousands separators are allowed but currency symbols are not. Per definire in modo esplicito gli elementi, ad esempio simboli di valuta, separatori delle migliaia e spazi vuoti, che possono essere presenti in s
, usare l' TryParse(String, NumberStyles, IFormatProvider, Single) Overload del metodo.To explicitly define the elements (such as currency symbols, thousands separators, and white space) that can be present in s
, use the TryParse(String, NumberStyles, IFormatProvider, Single) method overload.
Il s
parametro viene analizzato utilizzando le informazioni di formattazione in un NumberFormatInfo oggetto inizializzato per le impostazioni cultura correnti del sistema.The s
parameter is parsed using the formatting information in a NumberFormatInfo object that is initialized for the current system culture. Per altre informazioni, vedere NumberFormatInfo.CurrentInfo.For more information, see NumberFormatInfo.CurrentInfo. Per analizzare una stringa usando le informazioni di formattazione di altre impostazioni cultura specificate, usare l' TryParse(String, NumberStyles, IFormatProvider, Single) Overload del metodo.To parse a string using the formatting information of some other specified culture, use the TryParse(String, NumberStyles, IFormatProvider, Single) method overload.
In genere, se si passa il Single.TryParse metodo a una stringa creata chiamando il Single.ToString metodo, Single viene restituito il valore originale.Ordinarily, if you pass the Single.TryParse method a string that is created by calling the Single.ToString method, the original Single value is returned. Tuttavia, a causa di una perdita di precisione, i valori potrebbero non essere uguali.However, because of a loss of precision, the values may not be equal.
Se non s
è compreso nell'intervallo del Single tipo di dati, il metodo restituisce false
su .NET Framework e .NET Core 2,2 e versioni precedenti.If s
is out of range of the Single data type, the method returns false
on .NET Framework and .NET Core 2.2 and earlier versions. In .NET Core 3,0 e versioni successive, restituisce Single.NegativeInfinity se s
è minore di Single.MinValue e Single.PositiveInfinity se s
è maggiore di Single.MaxValue .On .NET Core 3.0 and later versions, it returns Single.NegativeInfinity if s
is less than Single.MinValue and Single.PositiveInfinity if s
is greater than Single.MaxValue.
Se viene rilevato un separatore nel s
parametro durante un'operazione di analisi e la valuta o il numero separatore decimale e di gruppo è identico, l'operazione di analisi presuppone che il separatore sia un separatore decimale anziché un separatore di gruppo.If a separator is encountered in the s
parameter during a parse operation, and the applicable currency or number decimal and group separators are the same, the parse operation assumes that the separator is a decimal separator rather than a group separator. Per ulteriori informazioni sui separatori, vedere CurrencyDecimalSeparator , NumberDecimalSeparator , CurrencyGroupSeparator e NumberGroupSeparator .For more information about separators, see CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparator, and NumberGroupSeparator.
Vedi anche
Si applica a
TryParse(ReadOnlySpan<Char>, Single)
Converte la rappresentazione stringa di un numero in un intervallo di caratteri nel numero a virgola mobile a precisione singola equivalente.Converts the string representation of a number in a character span to its single-precision floating-point number equivalent. Un valore restituito indica se la conversione è riuscita o meno.A return value indicates whether the conversion succeeded or failed.
public:
static bool TryParse(ReadOnlySpan<char> s, [Runtime::InteropServices::Out] float % result);
public static bool TryParse (ReadOnlySpan<char> s, out float result);
static member TryParse : ReadOnlySpan<char> * single -> bool
Public Shared Function TryParse (s As ReadOnlySpan(Of Char), ByRef result As Single) As Boolean
Parametri
- s
- ReadOnlySpan<Char>
>Intervallo di caratteri che contiene la rappresentazione stringa del numero da convertire.>A character span that contains the string representation of the number to convert.
- result
- Single
Al termine, questo metodo contiene il numero a virgola mobile a precisione singola equivalente al parametro s
se la conversione ha esito positivo oppure zero se la conversione non riesce.When this method returns, contains the single-precision floating-point number equivalent of the s
parameter, if the conversion succeeded, or zero if the conversion failed. La conversione non riesce se il parametro s
è null
o vuoto oppure non è un numero in un formato valido.The conversion fails if the s
parameter is null
or empty or is not a number in a valid format. Se è un numero valido minore di MinValue, result
è NegativeInfinity.If is a valid number less than MinValue, result
is NegativeInfinity. Se è un numero valido maggiore di MaxValue, result
è PositiveInfinity.If is a valid number greater than MaxValue, result
is PositiveInfinity. Questo parametro viene passato non inizializzato. Qualsiasi valore fornito in origine in result
verrà sovrascritto.This parameter is passed uninitialized; any value originally supplied in result
will be overwritten.
Restituisce
true
se s
è stato convertito correttamente; in caso contrario, false
.true
if s
was converted successfully; otherwise, false
.
Commenti
In .NET Core 3,0 e versioni successive, i valori troppo grandi per essere rappresentati vengono arrotondati a PositiveInfinity o NegativeInfinity come richiesto dalla specifica IEEE 754.In .NET Core 3.0 and later, values that are too large to represent are rounded to PositiveInfinity or NegativeInfinity as required by the IEEE 754 specification. Nelle versioni precedenti, incluse .NET Framework, l'analisi di un valore troppo grande per rappresentare il risultato è un errore.In prior versions, including .NET Framework, parsing a value that was too large to represent resulted in failure.
Si applica a
TryParse(String, NumberStyles, IFormatProvider, Single)
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 a precisione singola equivalente.Converts the string representation of a number in a specified style and culture-specific format to its single-precision floating-point number equivalent. Un valore restituito indica se la conversione è riuscita o meno.A return value indicates whether the conversion succeeded or failed.
public:
static bool TryParse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] float % result);
public static bool TryParse (string s, System.Globalization.NumberStyles style, IFormatProvider provider, out float result);
public static bool TryParse (string? s, System.Globalization.NumberStyles style, IFormatProvider? provider, out float? result);
static member TryParse : string * System.Globalization.NumberStyles * IFormatProvider * single -> bool
Public Shared Function TryParse (s As String, style As NumberStyles, provider As IFormatProvider, ByRef result As Single) As Boolean
Parametri
- s
- String
Stringa che rappresenta un numero da convertire.A string representing a number to convert.
- style
- NumberStyles
Combinazione bit per bit di valori di enumerazione che indica il formato consentito di s
.A bitwise combination of enumeration values that indicates the permitted format of s
. Un valore tipico da specificare è Float combinato con AllowThousands.A typical value to specify is Float combined with AllowThousands.
- provider
- IFormatProvider
Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura relativamente a s
.An object that supplies culture-specific formatting information about s
.
- result
- Single
Quando questo metodo viene restituito, contiene il numero a virgola mobile a precisione singola equivalente al valore numerico o al simbolo contenuto in s
, se la conversione ha esito positivo oppure zero se la conversione non riesce.When this method returns, contains the single-precision floating-point number equivalent to the numeric value or symbol contained in s
, if the conversion succeeded, or zero if the conversion failed. La conversione non riesce se il parametro s
è null
o Empty, se non è in un formato conforme a style
oppure se style
non è una combinazione valida di costanti di enumerazione NumberStyles.The conversion fails if the s
parameter is null
or Empty, is not in a format compliant with style
, or if style
is not a valid combination of NumberStyles enumeration constants. Non riesce neanche in .NET Framework o .NET Core 2.2 e versioni precedenti se s
rappresenta un numero minore di MinValue o maggiore di MaxValue.It also fails on .NET Framework or .NET Core 2.2 and earlier versions if s
represents a number less than MinValue or greater than MaxValue. Questo parametro viene passato non inizializzato. Qualsiasi valore fornito in origine in result
verrà sovrascritto.This parameter is passed uninitialized; any value originally supplied in result
will be overwritten.
Restituisce
true
se s
è stato convertito correttamente; in caso contrario, false
.true
if s
was converted successfully; otherwise, false
.
Eccezioni
style
non è un valore di NumberStyles.style
is not a NumberStyles value.
-oppure--or-
style
è il valore di AllowHexSpecifier.style
is the AllowHexSpecifier value.
Esempio
Nell'esempio seguente viene illustrato l'uso del Single.TryParse(String, NumberStyles, IFormatProvider, Single) metodo per analizzare la rappresentazione di stringa di numeri con uno stile particolare e che vengono formattati usando le convenzioni di impostazioni cultura specifiche.The following example demonstrates the use of the Single.TryParse(String, NumberStyles, IFormatProvider, Single) method to parse the string representation of numbers that have a particular style and are formatted using the conventions of a particular culture.
string value;
System.Globalization.NumberStyles style;
System.Globalization.CultureInfo culture;
float number;
// Parse currency value using en-GB culture.
value = "£1,097.63";
style = System.Globalization.NumberStyles.Number |
System.Globalization.NumberStyles.AllowCurrencySymbol;
culture = System.Globalization.CultureInfo.CreateSpecificCulture("en-GB");
if (Single.TryParse(value, style, culture, out number))
Console.WriteLine("Converted '{0}' to {1}.", value, number);
else
Console.WriteLine("Unable to convert '{0}'.", value);
value = "1345,978";
style = System.Globalization.NumberStyles.AllowDecimalPoint;
culture = System.Globalization.CultureInfo.CreateSpecificCulture("fr-FR");
if (Single.TryParse(value, style, culture, out number))
Console.WriteLine("Converted '{0}' to {1}.", value, number);
else
Console.WriteLine("Unable to convert '{0}'.", value);
value = "1.345,978";
style = System.Globalization.NumberStyles.AllowDecimalPoint |
System.Globalization.NumberStyles.AllowThousands;
culture = System.Globalization.CultureInfo.CreateSpecificCulture("es-ES");
if (Single.TryParse(value, style, culture, out number))
Console.WriteLine("Converted '{0}' to {1}.", value, number);
else
Console.WriteLine("Unable to convert '{0}'.", value);
value = "1 345,978";
if (Single.TryParse(value, style, culture, out number))
Console.WriteLine("Converted '{0}' to {1}.", value, number);
else
Console.WriteLine("Unable to convert '{0}'.", value);
// The example displays the following output:
// Converted '£1,097.63' to 1097.63.
// Converted '1345,978' to 1345.978.
// Converted '1.345,978' to 1345.978.
// Unable to convert '1 345,978'.
Dim value As String
Dim style As System.Globalization.NumberStyles
Dim culture As System.Globalization.CultureInfo
Dim number As Single
' Parse currency value using en-GB culture.
value = "£1,097.63"
style = System.Globalization.NumberStyles.Number Or _
System.Globalization.NumberStyles.AllowCurrencySymbol
culture = System.Globalization.CultureInfo.CreateSpecificCulture("en-GB")
If Single.TryParse(value, style, culture, number) Then
Console.WriteLine("Converted '{0}' to {1}.", value, number)
Else
Console.WriteLine("Unable to convert '{0}'.", value)
End If
value = "1345,978"
style = System.Globalization.NumberStyles.AllowDecimalPoint
culture = System.Globalization.CultureInfo.CreateSpecificCulture("fr-FR")
If Single.TryParse(value, style, culture, number) Then
Console.WriteLine("Converted '{0}' to {1}.", value, number)
Else
Console.WriteLine("Unable to convert '{0}'.", value)
End If
value = "1.345,978"
style = System.Globalization.NumberStyles.AllowDecimalPoint Or _
System.Globalization.NumberStyles.AllowThousands
culture = System.Globalization.CultureInfo.CreateSpecificCulture("es-ES")
If Single.TryParse(value, style, culture, number) Then
Console.WriteLine("Converted '{0}' to {1}.", value, number)
Else
Console.WriteLine("Unable to convert '{0}'.", value)
End If
value = "1 345,978"
If Single.TryParse(value, style, culture, number) Then
Console.WriteLine("Converted '{0}' to {1}.", value, number)
Else
Console.WriteLine("Unable to convert '{0}'.", value)
End If
' The example displays the following output:
' Converted '£1,097.63' to 1097.63.
' Converted '1345,978' to 1345.978.
' Converted '1.345,978' to 1345.978.
' Unable to convert '1 345,978'.
Commenti
In .NET Core 3,0 e versioni successive, i valori troppo grandi per essere rappresentati vengono arrotondati a PositiveInfinity o NegativeInfinity come richiesto dalla specifica IEEE 754.In .NET Core 3.0 and later, values that are too large to represent are rounded to PositiveInfinity or NegativeInfinity as required by the IEEE 754 specification. Nelle versioni precedenti, incluse .NET Framework, l'analisi di un valore troppo grande per rappresentare il risultato è un errore.In prior versions, including .NET Framework, parsing a value that was too large to represent resulted in failure.
Questo overload è diverso dal Parse(String, NumberStyles, IFormatProvider) Metodo restituendo un valore booleano che indica se l'operazione di analisi ha avuto esito positivo anziché restituire il valore numerico analizzato.This overload differs from the Parse(String, NumberStyles, IFormatProvider) method by returning a Boolean value that indicates whether the parse operation succeeded instead of returning the parsed numeric value. Elimina la necessità di utilizzare la gestione delle eccezioni per verificare un oggetto FormatException nel caso in cui s
non sia valido e non possa essere analizzato correttamente.It eliminates the need to use exception handling to test for a FormatException in the event that s
is invalid and cannot be successfully parsed.
Il style
parametro definisce il formato consentito del s
parametro affinché l'operazione di analisi abbia esito positivo.The style
parameter defines the allowable format of the s
parameter for the parse operation to succeed. Deve essere una combinazione di flag di bit dell' NumberStyles enumerazione.It must be a combination of bit flags from the NumberStyles enumeration. I NumberStyles membri seguenti non sono supportati:The following NumberStyles members are not supported:
Il s
parametro può contenere PositiveInfinitySymbol , NegativeInfinitySymbol , NaNSymbol per le impostazioni cultura indicate da provider
.The s
parameter can contain PositiveInfinitySymbol, NegativeInfinitySymbol, NaNSymbol for the culture indicated by provider
. Inoltre, a seconda del valore di style
, il s
parametro può includere gli elementi seguenti:In addition, depending on the value of style
, the s
parameter may include the following elements:
WS [$] Sign [cifre integrali,] cifre integrali [. frazionarie-cifre] [e [segno] cifre esponenziali] [ws][ws] [$] [sign][integral-digits,]integral-digits[.fractional-digits][e[sign]exponential-digits][ws]
Gli elementi tra parentesi quadre ([e]) sono facoltativi.Elements in square brackets ([ and ]) are optional. La tabella seguente descrive i singoli elementi.The following table describes each element.
ElementoElement | DescrizioneDescription |
---|---|
wsws | Spazi vuoti facoltativi.Optional white space. Gli spazi vuoti possono essere visualizzati all'inizio di s se style include il NumberStyles.AllowLeadingWhite flag.White space can appear at the beginning of s if style includes the NumberStyles.AllowLeadingWhite flag. Può comparire alla fine di s se style include il NumberStyles.AllowTrailingWhite flag.It can appear at the end of s if style includes the NumberStyles.AllowTrailingWhite flag. |
$ | Simbolo di valuta specifico delle impostazioni cultura.A culture-specific currency symbol. La posizione nella stringa è definita dalle NumberFormatInfo.CurrencyNegativePattern NumberFormatInfo.CurrencyPositivePattern proprietà o dell' NumberFormatInfo oggetto restituito dal IFormatProvider.GetFormat metodo del provider parametro.Its position in the string is defined by the NumberFormatInfo.CurrencyNegativePattern or NumberFormatInfo.CurrencyPositivePattern properties of the NumberFormatInfo object returned by the IFormatProvider.GetFormat method of the provider parameter. Il simbolo di valuta può essere visualizzato in s se style include il NumberStyles.AllowCurrencySymbol flag.The currency symbol can appear in s if style includes the NumberStyles.AllowCurrencySymbol flag. |
signsign | Segno facoltativo.An optional sign. Il segno può apparire all'inizio di s se style include il NumberStyles.AllowLeadingSign flag e può apparire alla fine di s se style include il NumberStyles.AllowTrailingSign flag.The sign can appear at the beginning of s if style includes the NumberStyles.AllowLeadingSign flag, and it can appear at the end of s if style includes the NumberStyles.AllowTrailingSign flag. Le parentesi possono essere utilizzate in s per indicare un valore negativo se style include il NumberStyles.AllowParentheses flag.Parentheses can be used in s to indicate a negative value if style includes the NumberStyles.AllowParentheses flag. |
cifre integraliintegral-digits | Serie di cifre comprese tra 0 e 9 che specificano la parte integrale del numero.A series of digits ranging from 0 to 9 that specify the integral part of the number. Le cifre integrali possono essere assenti se sono presenti cifre frazionarie.Integral-digits can be absent if there are fractional-digits. |
,, | Simbolo di separatore delle migliaia specifico delle impostazioni cultura.A culture-specific thousands separator symbol. Il simbolo di separatore delle migliaia delle impostazioni cultura correnti può essere visualizzato in s se style include il NumberStyles.AllowThousands flag.The current culture's thousands separator symbol can appear in s if style includes the NumberStyles.AllowThousands flag. |
.. | Simbolo di virgola decimale specifico delle impostazioni cultura.A culture-specific decimal point symbol. Il simbolo della virgola decimale delle impostazioni cultura correnti può essere visualizzato in s se style include il NumberStyles.AllowDecimalPoint flag.The current culture's decimal point symbol can appear in s if style includes the NumberStyles.AllowDecimalPoint flag. |
cifre frazionariefractional-digits | Serie di cifre comprese tra 0 e 9 che specificano la parte frazionaria del numero.A series of digits ranging from 0 to 9 that specify the fractional part of the number. Le cifre frazionarie possono essere visualizzate in s se style include il NumberStyles.AllowDecimalPoint flag.Fractional digits can appear in s if style includes the NumberStyles.AllowDecimalPoint flag. |
ee | Il carattere e o E, che indica che s può rappresentare un numero utilizzando la notazione esponenziale.The e or E character, which indicates that s can represent a number using exponential notation. Il s parametro può rappresentare un numero nella notazione esponenziale se style include il NumberStyles.AllowExponent flag.The s parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag. |
cifre esponenzialiexponential-digits | Serie di cifre comprese tra 0 e 9 che specificano un esponente.A series of digits ranging from 0 to 9 that specify an exponent. |
Nota
Qualsiasi carattere di terminazione NUL (U + 0000) in s
viene ignorato dall'operazione di analisi, indipendentemente dal valore dell' style
argomento.Any terminating NUL (U+0000) characters in s
are ignored by the parsing operation, regardless of the value of the style
argument.
Una stringa con solo cifre (che corrisponde allo NumberStyles.None stile) viene sempre analizzata correttamente se è nell'intervallo del Single tipo.A string with digits only (which corresponds to the NumberStyles.None style) always parses successfully if it is in the range of the Single type. I membri rimanenti System.Globalization.NumberStyles controllano gli elementi che possono essere ma non devono essere presenti nella stringa di input.The remaining System.Globalization.NumberStyles members control elements that may be but are not required to be present in the input string. Nella tabella seguente viene indicato il modo NumberStyles in cui i singoli flag influiscono sugli elementi che possono essere presenti in s
.The following table indicates how individual NumberStyles flags affect the elements that may be present in s
.
Valore NumberStylesNumberStyles value | Elementi consentiti in s oltre a cifreElements permitted in s in addition to digits |
---|---|
None | Solo l'elemento a cifre integrali .The integral-digits element only. |
AllowDecimalPoint | L'elemento language .The . e elementi con cifre frazionarie .and fractional-digits elements. |
AllowExponent | Il s parametro può anche usare la notazione esponenziale.The s parameter can also use exponential notation. Questo flag supporta a sua volta valori nelle cifre integrali e esponenziali dei form; sono necessari flag aggiuntivi per analizzare correttamente le stringhe in notazione esponenziale con elementi come segni positivi o negativi e simboli di virgola decimale.This flag by itself supports values in the form integral-digits E exponential-digits; additional flags are needed to successfully parse strings in exponential notation with such elements as positive or negative signs and decimal point symbols. |
AllowLeadingWhite | Elemento WS all'inizio di s .The ws element at the beginning of s . |
AllowTrailingWhite | Elemento WS alla fine di s .The ws element at the end of s . |
AllowLeadingSign | Elemento Sign all'inizio di s .The sign element at the beginning of s . |
AllowTrailingSign | Elemento Sign alla fine di s .The sign element at the end of s . |
AllowParentheses | Elemento del segno sotto forma di parentesi che racchiudono il valore numerico.The sign element in the form of parentheses enclosing the numeric value. |
AllowThousands | Elemento .The , element. |
AllowCurrencySymbol | $ Elemento.The $ element. |
Currency | Tutti.All. Il s parametro non può rappresentare un numero esadecimale o un numero in notazione esponenziale.The s parameter cannot represent a hexadecimal number or a number in exponential notation. |
Float | Elemento WS all'inizio o alla fine di s , Sign all'inizio di s e .The ws element at the beginning or end of s , sign at the beginning of s , and the . simbolo.symbol. Il s parametro può anche usare la notazione esponenziale.The s parameter can also use exponential notation. |
Number | Gli ws sign elementi separatore,, Miles (,) e separatore decimale (.).The ws , sign , thousands separator (,), and decimal point (.) elements. |
Any | Tutti gli stili, ad eccezione s di non possono rappresentare un numero esadecimale.All styles, except s cannot represent a hexadecimal number. |
Il provider
parametro è un' IFormatProvider implementazione il cui GetFormat metodo restituisce un NumberFormatInfo oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura.The provider
parameter is an IFormatProvider implementation whose GetFormat method returns a NumberFormatInfo object that provides culture-specific formatting information. Quando il TryParse(String, NumberStyles, IFormatProvider, Single) metodo viene richiamato, chiama il provider
metodo del parametro GetFormat e lo passa a un Type oggetto che rappresenta il NumberFormatInfo tipo.When the TryParse(String, NumberStyles, IFormatProvider, Single) method is invoked, it calls the provider
parameter's GetFormat method and passes it a Type object that represents the NumberFormatInfo type. Il GetFormat metodo restituisce quindi l' NumberFormatInfo oggetto che fornisce informazioni sul formato del s
parametro.The GetFormat method then returns the NumberFormatInfo object that provides information about the format of the s
parameter. Esistono tre modi per usare il provider
parametro per fornire informazioni di formattazione personalizzate all'operazione di analisi:There are three ways to use the provider
parameter to supply custom formatting information to the parse operation:
È possibile passare un CultureInfo oggetto che rappresenta le impostazioni cultura che forniscono informazioni di formattazione.You can pass a CultureInfo object that represents the culture that supplies formatting information. Il GetFormat metodo restituisce l' NumberFormatInfo oggetto che fornisce informazioni sulla formattazione numerica per tali impostazioni cultura.Its GetFormat method returns the NumberFormatInfo object that provides numeric formatting information for that culture.
È possibile passare l' NumberFormatInfo oggetto effettivo che fornisce informazioni sulla formattazione numerica.You can pass the actual NumberFormatInfo object that provides numeric formatting information. (L'implementazione di GetFormat restituisce solo se stessa).(Its implementation of GetFormat just returns itself.)
È possibile passare un oggetto personalizzato che implementa IFormatProvider .You can pass a custom object that implements IFormatProvider. Il GetFormat metodo crea un'istanza di e restituisce l' NumberFormatInfo oggetto che fornisce informazioni sulla formattazione.Its GetFormat method instantiates and returns the NumberFormatInfo object that provides formatting information.
Se provider
è null
, la formattazione di s
viene interpretata in base all' NumberFormatInfo oggetto delle impostazioni cultura correnti.If provider
is null
, the formatting of s
is interpreted based on the NumberFormatInfo object of the current culture.
Se non s
è compreso nell'intervallo del Single tipo di dati, il metodo genera un'eccezione OverflowException su .NET Framework e .NET Core 2,2 e versioni precedenti.If s
is out of range of the Single data type, the method throws an OverflowException on .NET Framework and .NET Core 2.2 and earlier versions. In .NET Core 3,0 e versioni successive, restituisce Single.NegativeInfinity se s
è minore di Single.MinValue e Single.PositiveInfinity se s
è maggiore di Single.MaxValue .On .NET Core 3.0 and later versions, it returns Single.NegativeInfinity if s
is less than Single.MinValue and Single.PositiveInfinity if s
is greater than Single.MaxValue.
Se viene rilevato un separatore nel s
parametro durante un'operazione di analisi e la valuta o il numero separatore decimale e di gruppo è identico, l'operazione di analisi presuppone che il separatore sia un separatore decimale anziché un separatore di gruppo.If a separator is encountered in the s
parameter during a parse operation, and the applicable currency or number decimal and group separators are the same, the parse operation assumes that the separator is a decimal separator rather than a group separator. Per ulteriori informazioni sui separatori, vedere CurrencyDecimalSeparator , NumberDecimalSeparator , CurrencyGroupSeparator e NumberGroupSeparator .For more information about separators, see CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparator, and NumberGroupSeparator.