How to convert a decimal value to a string in C#
Overview
Decimal.ToString() is a method in C# that is called on decimal values. It converts a numeric value that is a decimal to a string.
Syntax
dec.ToString()
Parameters
dec: This is the decimal value that we want to convert to a string.
Return value
The value returned is a string representation of dec.
Code example
// use Systemusing System;// create classclass DecimalToString{// main methodstatic void Main(){// create decimal valuesdecimal d1 = 34.5m;decimal d2 = 2.4356345m;decimal d3 = 10.34m;// convert to Strings// and print valueConsole.WriteLine("Value = {0}, type = {1}",d1.ToString(),d1.ToString().GetType());Console.WriteLine("Value = {0}, type = {1}",d2.ToString(),d2.ToString().GetType());Console.WriteLine("Value = {0}, type = {1}",d3.ToString(),d3.ToString().GetType());}}
Explanation
Here is a line-by-line explanation of the above code:
-
Lines 10-12: We create variables
d1,d2, andd3of type decimal and assign decimal values to them. -
Lines 16-26: We convert each value to a string using the
ToString()method. Then we print the converted values and their type using theGetType()method.
As we can see in the output, the decimal values are converted to strings.