Convert.ToDecimal Method (String)

July 28, 2014

Converts the specified String representation of a number to an equivalent Decimal number.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

public static decimal ToDecimal(
	string value
)

Parameters

value
Type: System.String
A String containing a number to convert.

Return Value

Type: System.Decimal
A Decimal number equivalent to the value of value.
-or-
Zero if value is null.

ExceptionCondition
FormatException

value is not a number in a valid format.

OverflowException

value represents a number less than MinValue or greater than MaxValue.

The return value is the result of invoking the Decimal.Parse method on value.

If you prefer not to handle an exception if the conversion fails, you can call the Decimal.TryParse method instead. It returns a Boolean value that indicates whether the conversion succeeded or failed.

The following code sample illustrates the use of ToDecimal, by attempting to convert a String to a Decimal and throwing any of the possible exceptions that may arise during the conversion.


public void ConvertStringDecimal(string stringVal)
{
   decimal decimalVal = 0;

   try
   {
      decimalVal = System.Convert.ToDecimal(stringVal);
      outputBlock.Text += String.Format(
         "The string as a decimal is {0}.", decimalVal) + "\n";
   }
   catch (System.OverflowException)
   {
      outputBlock.Text += String.Format(
         "The conversion from string to decimal overflowed.") + "\n";
   }
   catch (System.FormatException)
   {
      outputBlock.Text += String.Format(
         "The string is not formatted as a decimal.") + "\n";
   }
   catch (System.ArgumentNullException)
   {
      outputBlock.Text += String.Format(
         "The string is null.") + "\n";
   }

   // Decimal to string conversion will not overflow.
   stringVal = System.Convert.ToString(decimalVal);
   outputBlock.Text += String.Format(
      "The decimal as a string is {0}.", stringVal) + "\n";
}


Windows Phone OS

Supported in: 8.1, 8.0, 7.1, 7.0

Windows Phone

Show:
© 2014 Microsoft