C# | Decimal.ToString Method | Set -1
Last Updated :
29 Mar, 2019
Decimal.ToString() Method is used to convert the numeric value of the current instance to its equivalent string representation using the specified culture-specific format information. There are 4 methods in the overload list of this method as follows:
- ToString() Method
- ToString(IFormatProvider) Method
- ToString(String, IFormatProvider) Method
- ToString(String) Method
Here, we will discuss the first two methods.
ToString() Method
This method is used to convert the numeric value of the current instance to its equivalent string representation.
Syntax: public override string ToString ();
Return Value: This method returns a string which represents the value of the current instance.
Below programs illustrate the use of Decimal.ToString() Method:
Example 1:
using System;
class GFG {
public static void Main()
{
decimal value = 7922816251426433759354.39503305M;
string str = value.ToString();
Console.WriteLine( "String value is {0}" , str);
}
}
|
Output:
String value is 7922816251426433759354.3950330
Example 2:
using System;
using System.Globalization;
class GFG {
public static void Main()
{
Console.WriteLine( "Equivalent String values are:" );
get (20);
get (30);
get (40);
get (4294967295);
}
public static void get ( decimal value)
{
string str = value.ToString();
Console.WriteLine( "String value is {0}" , str);
}
}
|
Output:
Equivalent String values are:
String value is 20
String value is 30
String value is 40
String value is 4294967295
ToString(String) Method
This method is used to convert the numeric value of the current instance to its equivalent string representation, using the specified format.
Syntax: public string ToString (string format);
Here, it takes a standard or custom numeric format string.
Return Value: This method returns the string representation of the value of the current instance as specified by format.
Exceptions: This method throws FormatException if format is invalid.
Example 1:
using System;
class GFG {
public static void Main()
{
try {
decimal value = 16325.62m;
string s = "E04" ;
string str = value.ToString(s);
Console.WriteLine( "String value is {0}" , str);
}
catch (FormatException e)
{
Console.WriteLine( "Format is invalid." );
Console.Write( "Exception Thrown: " );
Console.Write( "{0}" , e.GetType(), e.Message);
}
}
}
|
Output:
String value is 1.6326E+004
Example 2: For FormatException
using System;
class GFG {
public static void Main()
{
try {
decimal value = 16325.62m;
string s = "a" ;
string str = value.ToString(s);
Console.WriteLine( "String value is {0}" , str);
}
catch (FormatException e)
{
Console.WriteLine( "Format is invalid." );
Console.Write( "Exception Thrown: " );
Console.Write( "{0}" , e.GetType(), e.Message);
}
}
}
|
Output:
Format is invalid.
Exception Thrown: System.FormatException
Reference:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...