C# Decimal TryParse(String, Decimal)

Description

Decimal TryParse(String, Decimal) converts the string representation of a number to its Decimal equivalent. A return value indicates whether the conversion succeeded or failed.

Syntax

Decimal.TryParse(String, Decimal) has the following syntax.


public static bool TryParse(
  string s,
  out decimal result
)

Parameters

Decimal.TryParse(String, Decimal) has the following parameters.

  • s - The string representation of the number to convert.
  • result - 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 null or String.Empty, is not a number in a valid format, or represents a number less than MinValue or greater than MaxValue. This parameter is passed uninitialized.

Returns

Decimal.TryParse(String, Decimal) method returns true if s was converted successfully; otherwise, false.

Example

The following example uses the Decimal.TryParse(String, Decimal) method to convert the string representations of numeric values to Decimal values. It assumes that en-US is the current culture.


using System;/*from w w  w .  j a v  a2 s .  c  om*/
public class MainClass{
  public static void Main(String[] argv){  
    string value;
    decimal number;
    
    // Parse a floating-point value with a thousands separator. 
    value = "1,643.57";
    if (Decimal.TryParse(value, out number))
       System.Console.WriteLine(number);
    else
       System.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))
       System.Console.WriteLine(number);
    else
       System.Console.WriteLine("Unable to parse '{0}'.", value);   
    
    // Parse value in exponential notation. 
    value = "-1.643e6";
    if (Decimal.TryParse(value, out number))
       System.Console.WriteLine(number);
    else
       System.Console.WriteLine("Unable to parse '{0}'.", value);   
    
    // Parse a negative integer value. 
    value = "-1689346178821";
    if (Decimal.TryParse(value, out number))
       System.Console.WriteLine(number);
    else
       System.Console.WriteLine("Unable to parse '{0}'.", value);   
    
    
  }
}
    

The code above generates the following result.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version