Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
decimal
string
communitycreator

How to convert a decimal value to a string in C#

Theodore Kelechukwu Onyejiaku

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 System
using System;
// create class
class DecimalToString
{
    // main method
    static void Main()
    {
        // create decimal values
        decimal d1 = 34.5m;
        decimal d2 = 2.4356345m;
        decimal d3 = 10.34m;

        // convert to Strings
        // and print value
        Console.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());
    }
}
Convert decimal values to strings in C#

Explanation

Here is a line-by-line explanation of the above code:

  • Lines 10-12: We create variables d1, d2, and d3 of 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 the GetType() method.

As we can see in the output, the decimal values are converted to strings.

RELATED TAGS

c#
decimal
string
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring