Single.TryParse Method (System) (original) (raw)
Source:
Source:
Source:
Source:
Converts the string representation of a number in a specified style and culture-specific format to its single-precision floating-point number equivalent. 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(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] float % result) = System::Numerics::INumberBase<float>::TryParse;
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
Parameters
s
A string representing a number to convert.
style
A bitwise combination of enumeration values that indicates the permitted format of s
. A typical value to specify is Float combined with AllowThousands.
provider
An object that supplies culture-specific formatting information about s
.
result
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. 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. It also fails on .NET Framework or .NET Core 2.2 and earlier versions if s
represents a number less than Single.MinValue or greater than Single.MaxValue. This parameter is passed uninitialized; any value originally supplied in result
will be overwritten.
Returns
true
if s
was converted successfully; otherwise, false
.
Exceptions
Examples
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'.
// Parse currency value using en-GB culture.
let value = "£1,097.63"
let style = System.Globalization.NumberStyles.Number ||| System.Globalization.NumberStyles.AllowCurrencySymbol
let culture = System.Globalization.CultureInfo.CreateSpecificCulture "en-GB"
match Single.TryParse(value, style, culture) with
| true, number ->
printfn $"Converted '{value}' to {number}."
| _ ->
printfn $"Unable to convert '{value}'."
let value = "1345,978"
let style = System.Globalization.NumberStyles.AllowDecimalPoint
let culture = System.Globalization.CultureInfo.CreateSpecificCulture "fr-FR"
match Single.TryParse(value, style, culture) with
| true, number ->
printfn $"Converted '{value}' to {number}."
| _ ->
printfn $"Unable to convert '{value}'."
let value = "1.345,978"
let style = System.Globalization.NumberStyles.AllowDecimalPoint ||| System.Globalization.NumberStyles.AllowThousands
let culture = System.Globalization.CultureInfo.CreateSpecificCulture "es-ES"
match Single.TryParse(value, style, culture) with
| true, number ->
printfn $"Converted '{value}' to {number}."
| _ ->
printfn $"Unable to convert '{value}'."
let value = "1 345,978"
match Single.TryParse(value, style, culture) with
| true, number ->
printfn $"Converted '{value}' to {number}."
| _ ->
printfn $"Unable to convert '{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'.
Remarks
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. In prior versions, including .NET Framework, parsing a value that was too large to represent resulted in failure.
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. 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.
The style
parameter defines the allowable format of the s
parameter for the parse operation to succeed. It must be a combination of bit flags from the NumberStyles enumeration. The following NumberStyles members are not supported:
The s
parameter can contain PositiveInfinitySymbol, NegativeInfinitySymbol, NaNSymbol for the culture indicated by provider
. In addition, depending on the value of style
, the s
parameter may include the following elements:
[ws] [$] [sign][integral-digits,]integral-digits[.fractional-digits][e[sign]exponential-digits][ws]
Elements in square brackets ([ and ]) are optional. The following table describes each element.
Element | Description |
---|---|
ws | Optional white space. White space can appear at the beginning of s if style includes the NumberStyles.AllowLeadingWhite flag. It can appear at the end of s if style includes the NumberStyles.AllowTrailingWhite flag. |
$ | A culture-specific currency symbol. 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. The currency symbol can appear in s if style includes the NumberStyles.AllowCurrencySymbol flag. |
sign | An optional sign. 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. Parentheses can be used in s to indicate a negative value if style includes the NumberStyles.AllowParentheses flag. |
integral-digits | A series of digits ranging from 0 to 9 that specify the integral part of the number. Integral-digits can be absent if there are fractional-digits. |
, | A culture-specific thousands separator symbol. The current culture's thousands separator symbol can appear in s if style includes the NumberStyles.AllowThousands flag. |
. | A culture-specific decimal point symbol. The current culture's decimal point symbol can appear in s if style includes the NumberStyles.AllowDecimalPoint flag. |
fractional-digits | A series of digits ranging from 0 to 9 that specify the fractional part of the number. Fractional digits can appear in s if style includes the NumberStyles.AllowDecimalPoint flag. |
e | The e or E character, which indicates that s can represent a number using exponential notation. The s parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag. |
exponential-digits | A series of digits ranging from 0 to 9 that specify an exponent. |
Note
Any terminating NUL (U+0000) characters in s
are ignored by the parsing operation, regardless of the value of the style
argument.
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. The remaining System.Globalization.NumberStyles members control elements that may be but are not required to be present in the input string. The following table indicates how individual NumberStyles flags affect the elements that may be present in s
.
NumberStyles value | Elements permitted in s in addition to digits |
---|---|
None | The integral-digits element only. |
AllowDecimalPoint | The . and fractional-digits elements. |
AllowExponent | The s parameter can also use exponential notation. 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 | The ws element at the beginning of s. |
AllowTrailingWhite | The ws element at the end of s. |
AllowLeadingSign | The sign element at the beginning of s. |
AllowTrailingSign | The sign element at the end of s. |
AllowParentheses | The sign element in the form of parentheses enclosing the numeric value. |
AllowThousands | The , element. |
AllowCurrencySymbol | The $ element. |
Currency | All. The s parameter cannot represent a hexadecimal number or a number in exponential notation. |
Float | The ws element at the beginning or end of s, sign at the beginning of s, and the . symbol. The s parameter can also use exponential notation. |
Number | The ws, sign, thousands separator (,), and decimal point (.) elements. |
Any | All styles, except s cannot represent a hexadecimal number. |
The provider
parameter is an IFormatProvider implementation whose GetFormat method returns a NumberFormatInfo object that provides culture-specific formatting information. 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. The GetFormat method then returns the NumberFormatInfo object that provides information about the format of the s
parameter. There are three ways to use the provider
parameter to supply custom formatting information to the parse operation:
- You can pass a CultureInfo object that represents the culture that supplies formatting information. Its GetFormat method returns the NumberFormatInfo object that provides numeric formatting information for that culture.
- You can pass the actual NumberFormatInfo object that provides numeric formatting information. (Its implementation of GetFormat just returns itself.)
- You can pass a custom object that implements IFormatProvider. Its GetFormat method instantiates and returns the NumberFormatInfo object that provides formatting information.
If provider
is null
, the formatting of s
is interpreted based on the NumberFormatInfo object of the current culture.
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. 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.
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. For more information about separators, see CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparator, and NumberGroupSeparator.