Format a String to Currency in C#

  1. Format a String to Currency With the String.Format() Method in C
  2. Format a String to Currency With the ToString() Method in C

This tutorial will discuss the methods of formatting a string variable to currency in C#.

Format a String to Currency With the String.Format() Method in C

The String.Format() method formats a string in C#. We can use the {0:C} format specifier inside the String.Format() method to convert the string variable to a currency format. The following code example shows us how to format a string to currency format with the String.Format() method in C#.

using System;

namespace string_to_currency
{
    class Program
    {
        static void Main(string[] args)
        {
            decimal money = 1234.56M;
            string mstring = String.Format("{0:C}", money);
            Console.WriteLine(mstring);
        }
    }
}

Output:

$1,234.56

In the above code, we converted the decimal variable money to the string variable mstring in the currency format with the String.Format() method in C#. We used the format specifier {0:C} to format the money in a currency formatted string.

Format a String to Currency With the ToString() Method in C

The ToString() method is used to convert any data type to a string variable in C#. We can use the C string format specifier to format the resultant string variable in currency format. The following code example shows us how to format a string to currency format with the ToString() method in C#.

using System;

namespace string_to_currency
{
    class Program
    {
        static void Main(string[] args)
        {
            decimal money = 1234.56M;
            string mstring = money.ToString("C");
            Console.WriteLine(mstring);
        }
    }
}

Output:

$1,234.56

In the above code, we converted the decimal variable money to the string variable mstring in the currency format with the ToString() method in C#. We used the format specifier C inside the ToString() method to format the money in a currency formatted string.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Csharp String

  • Add a Tab to a String in C#