Description: These are simple examples to show you how to use TryParse
Parameters
s
Type: System..::.String
The string representation of the number to convert.
- result
- Type: System..::.Decimal%
When this method returns, contains the Decimal number that is equivalent to the numeric value contained in s, if the conversion succeeded, or is zero if the conversion failed. The conversion fails if the s parameter is nullNothingnullptra null reference (Nothing in Visual Basic), is not a number in a valid format, or represents a number less than MinValue or greater than MaxValue. This parameter is passed uninitialized.
Return Value
Type:
System..::.Boolean true if s was converted successfully; otherwise, false.
Visual Basic
Dim value As String
Dim number As Decimal
' Parse a floating-point value with a thousands separator.
value = "1,643.57"
If Decimal.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 Decimal.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 Decimal.TryParse(value, number)
Console.WriteLine(number)
Else
Console.WriteLine("Unable to parse '{0}'.", value)
End If
' Parse a negative integer value.
value = "-1689346178821"
If Decimal.TryParse(value, number)
Console.WriteLine(number)
Else
Console.WriteLine("Unable to parse '{0}'.", value)
End If
' The example displays the following output to the console:
' 1643.57
' Unable to parse '$1,643.57'.
' Unable to parse '-1.643e6'.
' -1689346178821
C#
string value;
decimal number;
// Parse a floating-point value with a thousands separator.
value = "1,643.57";
if (Decimal.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 (Decimal.TryParse(value, out number))
Console.WriteLine(number);
else
Console.WriteLine("Unable to parse '{0}'.", value);
// Parse value in exponential notation.
value = "-1.643e6";
if (Decimal.TryParse(value, out number))
Console.WriteLine(number);
else
Console.WriteLine("Unable to parse '{0}'.", value);
// Parse a negative integer value.
value = "-1689346178821";
if (Decimal.TryParse(value, out number))
Console.WriteLine(number);
else
Console.WriteLine("Unable to parse '{0}'.", value);
// The example displays the following output to the console:
// 1643.57
// Unable to parse '$1,643.57'.
// Unable to parse '-1.643e6'.
// -1689346178821