C# Convert ToDecimal(Object)
Description
Convert ToDecimal(Object)
converts the value of the
specified object to an equivalent decimal number.
Syntax
Convert.ToDecimal(Object)
has the following syntax.
public static decimal ToDecimal(
Object value
)
Parameters
Convert.ToDecimal(Object)
has the following parameters.
value
- An object that implements the IConvertible interface, or null.
Returns
Convert.ToDecimal(Object)
method returns A decimal number that is equivalent to value, or 0 (zero) if value is null.
Example
The following example tries to convert each element in an object array to a Decimal value.
// w w w. j a va 2s . co m
using System;
public class MainClass{
public static void Main(String[] argv){
object[] values = { true, 'a', 123, 1.123e32, "9.78", "1e-02",
1.67e03, "A100", "1,123.67", DateTime.Now,
Double.MaxValue };
decimal result;
foreach (object value in values)
{
try {
result = Convert.ToDecimal(value);
Console.WriteLine("Converted the {0} value {1} to {2}.",
value.GetType().Name, value, result);
}
catch (OverflowException) {
Console.WriteLine("The {0} value {1} is out of range of the Decimal type.",
value.GetType().Name, value);
}
catch (FormatException) {
Console.WriteLine("The {0} value {1} is not recognized as a valid Decimal value.",
value.GetType().Name, value);
}
catch (InvalidCastException) {
Console.WriteLine("Conversion of the {0} value {1} to a Decimal is not supported.",
value.GetType().Name, value);
}
}
}
}
The code above generates the following result.