C# Convert ToDecimal(String)

Description

Convert ToDecimal(String) converts the specified string representation of a number to an equivalent decimal number.

Syntax

Convert.ToDecimal(String) has the following syntax.


public static decimal ToDecimal(
  string value
)

Parameters

Convert.ToDecimal(String) has the following parameters.

  • value - A string that contains a number to convert.

Returns

Convert.ToDecimal(String) method returns A decimal number that is equivalent to the number in value, or 0 (zero) if value is null.

Example

The following example illustrates the use of ToDecimal.


/*w  w  w. ja v  a 2 s .c  om*/
using System;
public class MainClass{
  public static void Main(String[] argv){  
            string stringVal = "123";
      decimal decimalVal = 0;
      
      try {
        decimalVal = System.Convert.ToDecimal(stringVal);
        System.Console.WriteLine(
          "The string as a decimal is {0}.", decimalVal);
      } 
      catch (System.OverflowException){
        System.Console.WriteLine(
          "The conversion from string to decimal overflowed.");
      }
      catch (System.FormatException) {
        System.Console.WriteLine(
          "The string is not formatted as a decimal.");
      }
      catch (System.ArgumentNullException) {
        System.Console.WriteLine(
          "The string is null.");
      }

      // Decimal to string conversion will not overflow.
      stringVal = System.Convert.ToString(decimalVal);
      System.Console.WriteLine(
        "The decimal as a string is {0}.", stringVal);

  }
}
    

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